Page 3 - Lesson Note-DFH-Binary & CSV File
P. 3
Where Do CSV Files Come From?
CSV files are normally created by programs that handle large amounts of data. They are a
convenient way to export data from spreadsheets and databases as well as import or use it
in other programs.
For example, you might export the results of a data mining program to a CSV file and then
import that into a spreadsheet to analyze the data, generate graphs for a presentation, or
prepare a report for publication.
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 easy to work with programmatically. Any language that supports text file
input and string manipulation (like Python) can work with CSV files directly.
CSV Functions
The CSV module includes all the necessary functions built in. They are:
csv.reader
csv.writer
Reading CSV Files
reader function generates a iterable reader object which pulls data from a CSV file
The reader function is designed to take each line of the file and make a list of all columns.
Then, you just choose the column you want the variable data for.
Writing to CSV Files
The writer() function will create an object suitable for writing. To iterate the data over the
rows, you will need to use the writerow() function.
csv.writer() returns a writer object responsible for converting the user’s data into delimited
strings on the given file-like object.
csvwriter.writerow(row)
Write the row parameter to the writer’s file object.
#1.Reading from csv file
import csv
f=open("XI_SC_ANN.csv")
recs=csv.reader(f) #CSV is an iterable object
for L in recs:
print(L)
f.close()