banner



How To Clean A Csv File In Python

Reading and Writing CSV File using Python


CSV (stands for comma separated values) format is a usually used information format used by spreadsheets. The csv module in Python'south standard library presents classes and methods to perform read/write operations on CSV files.

writer()

This part in csv module returns a author object that converts data into a delimited cord and stores in a file object. The office needs a file object with write permission equally a parameter. Every row written in the file issues a newline character. To prevent additional space between lines, newline parameter is set to ''.

The writer class has post-obit methods

writerow()

This office writes items in an iterable (listing, tuple or string) ,separating them nby comma character.

writerows()

This function takes a list of iterables every bit parameter and writes each item as a comma separated line of items in the file.

Post-obit example shows utilize of write() role. Kickoff a file is opened in 'w' mode. This file is used to obtain writer object. Each tuple in list of tuples is then written to file using writerow() method.

>>> import csv >>> persons=[('Lata',22,45),('Anil',21,56),('John',20,60)] >>> csvfile=open('persons.csv','w', newline='') >>> obj=csv.writer(csvfile) >>> for person in persons: obj.writerow(person) >>> csvfile.close()

This will create 'persons.csv' file in current directory. Information technology will show following data.

Lata,22,45 Anil,21,56 John,twenty,60

Instad of iterating over the list to write each row individually, we can use writerows() method.

>>> csvfile = open('persons.csv','w', newline='') >>> obj = csv.author(csvfile) >>> obj.writerows(persons) >>> obj.close()

read()

this function returns a reader object which returns an iterator of lines in the csv file. Using the regular for loop, all lines in the file are displayed in following example.

>>> csvfile=open('persons.csv','r', newline='') >>> obj=csv.reader(csvfile) >>> for row in obj: print (row) ['Lata', '22', '45'] ['Anil', '21', '56'] ['John', '20', '60']

Since reader object is an iterator, born side by side() function is also useful to display all lines in csv file.

>>> csvfile = open('persons.csv','r', newline='') >>> obj = csv.reader(csvfile) >>> while True: try: row=adjacent(obj) print (row) except StopIteration: pause

The csv module also defines a dialect grade. Dialect is set up of standards used to implement CSV protocol. The list of dialects available can exist obtained by list_dialects() role.

>>> csv.list_dialects() ['excel', 'excel-tab', 'unix']

DictWriter()

This function returns a DictWriter object. Information technology is like to writer object, but the rows are mapped to lexicon object. The function needs a file object with write permission and a list of keys used in dictionary as fieldnames parameter. This is used to write first line in the file as header.

writeheader()

This method writes list of keys in dictionary equally a comma separated line every bit first line in the file.

In following example, a list of lexicon items is defined. Each item in the list is a dictionary. Using writrows() method, they are written to file in comma separated way.

>>> persons=[{'proper noun':'Lata', 'age':22, 'marks':45}, {'proper noun':'Anil', 'age':21, 'marks':56}, {'proper noun':'John', 'age':20, 'marks':lx}] >>> csvfile=open up('persons.csv','due west', newline='') >>> fields=list(persons[0].keys()) >>> obj=csv.DictWriter(csvfile, fieldnames=fields) >>> obj.writeheader() >>> obj.writerows(persons) >>> csvfile.close()

The file shows following contents.

name,age,marks Lata,22,45 Anil,21,56 John,20,60

DictReader()

This function returns a DictReader object from the underlying CSV file. As in case of reader object, this 1 is as well an iterator, using which contents of the file are retrieved.

>>> csvfile = open('persons.csv','r', newline='') >>> obj = csv.DictReader(csvfile)

The class provides fieldnames attribute, returning the dictionary keys used every bit header of file.

>>> obj.fieldnames ['name', 'age', 'marks']

Use loop over the DictReader object to fetch individual dictionary objects.

>>> for row in obj: print (row)

This results in post-obit output.

OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')]) OrderedDict([('proper name', 'Anil'), ('age', '21'), ('marks', '56')]) OrderedDict([('name', 'John'), ('age', '20'), ('marks', 'lx')])

To convert OrderedDict object to normal dictionary, we have to first import OrderedDict from collections module.

>>> from collections import OrderedDict >>> r=OrderedDict([('proper name', 'Lata'), ('age', '22'), ('marks', '45')]) >>> dict(r) {'proper name': 'Lata', 'age': '22', 'marks': '45'}

In this commodity features of csv module take been explained.

raja

Published on 07-December-2018 06:58:08

  • Related Questions & Answers
  • Reading and writing binary file in C/C++
  • Reading and Writing Files in Python
  • Writing a CSV file in Coffee using OpenCSV
  • Writing data from database to .csv file
  • Writing a Pandas DataFrame to CSV file
  • Reading/Writing a MS Word file in PHP
  • Reading and Writing to text files in Python
  • Reading and writing Excel files using the openpyxl module in Python
  • Reading and Writing Files in Perl
  • Reading and Writing to text files in Python Program
  • How to open an Excel file with PHPExcel for both reading and writing?
  • Reading and Writing to text files in C#
  • What are reading and writing characters in C language?
  • Python - Writing to an excel file using openpyxl module
  • Reading images using Python?

Source: https://www.tutorialspoint.com/reading-and-writing-csv-file-using-python

Posted by: murrayhistoodespil.blogspot.com

0 Response to "How To Clean A Csv File In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel