Sunday, 7 May 2017

how to working with CSV files in python

how to working with CSV files in python:

  • csv stands for “comma-separated values/variables”
  • where the comma is what is known as a "delimiter."
  • A csv file is a human readable text file where each line has a number of fields, separated by commas or some other delimiter.
  • You can think of each line as a row and each field as a column.
  • in order to work with csv files, we are import csv module.
  • Each line in a csv file represents a row in the spreadsheet, and commas separate the cells in the row. For example, the spreadsheet example.xlsx

example.csv:

4/5/2015 13:34,Apples,73
4/5/2015 3:41,Cherries,85
4/6/2015 12:46,Pears,14
4/8/2015 8:59,Oranges,52
4/10/2015 2:07,Apples,152
4/10/2015 18:10,Bananas,23
4/10/2015 2:40,Strawberries,98

Reading a CSV File:


import csv

exampleFile = open('example.csv')

exampleReader = csv.reader(exampleFile)

exampleData = list(exampleReader)

print(exampleData)


output:

[['4/5/2015 13:34', 'Apples', '73'], ['4/5/2015 3:41', 'Cherries', '85'], ['4/6/2015 12:46', 'Pears', '14'], ['4/8/2015 8:59', 'Oranges', '52'], ['4/10/2015 2:07', 'Apples', '152'], ['4/10/2015 18:10', 'Bananas', '23'], ['4/10/2015 2:40', 'Strawberries', '98']] 

Writing a CSV File:

import csv

outputFile = open('output.csv', 'w', newline=' ')

outputWriter = csv.writer(outputFile)

outputWriter.writerow(['spam', 'eggs', 'bacon', 'ham'])

outputFile.close( )





No comments:

Post a Comment