03_01_csv-files-lesson-notes-optional-download_Files - CSV Files
03_01_csv-files-lesson-notes-optional-download_Files - CSV Files
Files
CSV Files
CSV Files
Python can work with files besides just text files. Comma Separated Value
(CSV) files are an example of a commonly used file format for storing data.
CSV files are similar to a spreadsheet in that data is stored in rows and
columns. Each row of data is on its own line in the file, and commas are
used to indicate a new column. Here is an example of a CSV file.
In order to read a CSV file, Python needs to import the csv module. If you
are importing a module, always start your code with the import
statements. The CSV file will be opened much like a text file, but Python
needs to run the file through a CSV reader.
import csv
reader = csv.reader(input_file)
for row in reader:
print(row)
challenge
import csv
Next
The first row of a CSV file is helpful because the header values provide
context for the data. However, the first row is not useful if you want to
know how many rows of data, or calculate the avg value, etc. The next
command allows Python to skip the first row before looping through the
CSV file.
import csv
challenge
import csv
challenge
The for loop has three variables: name, hr, and active. The first variable,
name, represents the first element in the list, the second variable, hr,
represents the second element of the list, and the third variable, active,
represents the third element. This is called unpacking.
import csv
challenge
Delimiters
Delimiters are a predefined character that separates one piece of
information from another. CSV files use commas as the delimiter by
default. However, this makes the file hard to read for humans. It is
possible to change the delimiter in Python (click here to see an example),
but your code must reflect this change.
Tab Delimiter
import csv
challenge
Writerow
Writing to a CSV file is similar to writing to a text file. Open the file and set
the mode to write ("w"). If the file does not exist, Python will create it. Send
content to the file with the method writerow. Like reading a CSV, you need
to import the csv module. Instead of using a reader, you need to use a
writter to write information to the file. When you read information from a
CSV file, it is a list of strings. So information written to a CSV file should
also be a list of strings.
import csv
challenge
Writerows
The writerow method writes only one row of information to a CSV file. The
writerows method can write several rows of information to a CSV file.
writerows takes either a list of strings (a single row of information) or a list
of lists of strings (many rows of information).
Writerows
import csv
challenge