py_handles_csv
reading and writing CSV files in python using csv and pandas module
What CSV Stands For ?
CSV stands for Comma Separated Values File is just like a plain file that uses a different approach for structuring data.
If you open a csv file in Sublime Text you will find simple plain text separated with commas
Example
id,name,email,amount,date,sent
1,Hopper,email-address,269,03 Sep at 21:14,False
2,Drake,email-address,690,03 Sep at 21:14,False
3,Adam,email-address,20,03 Sep at 21:14,False
4,Justin,email-address,199,03 Sep at 21:14,False
In general, the separator character is called a delimiter, and the comma is not the only one used. Other popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters. Properly parsing a CSV file requires us to know which delimiter is being used.
CSV files are very useful for handling large chunk of data and this type of data can be very easily handled with any programming language which supports string handling like python.
Python has built-in csv library for handling csv data. Using python csv library we can perform many tasks on csv files and csv data like reading, writing and processing data from csv files.
Reading CSV File
csv library has reader object for specifically reading purpose of csv files.
The with open() function in python opens any file including csv files in text
format, the text is then passed onto reader object which does all the processing of
the csv data.
We have a file employee_data.csv file which has values in comma seperated
format, reading_csvfile.py opens the file and reads data from it using csv library
reading_csvfile.py
import csv
with open('employee_data.csv') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
line_count += 1
print(f'Processed {line_count} lines.')