Text files aren’t the only thing that Python can read, but they’re the only thing that we don’t need any additional parsing library to understand. CSV files are an example of a text file that impose a structure to their data. CSV stands for Comma-Separated Values and CSV files are usually the way that data from spreadsheet software (like Microsoft Excel or Google Sheets) is exported into a portable format. A spreadsheet that looks like the following
Name | Username | |
---|---|---|
Roger Smith | rsmith | [email protected] |
Michelle Beck | mlbeck | [email protected] |
Ashley Barker | a_bark_x | [email protected] |
Lynn Gonzales | goodmanjames | [email protected] |
Jennifer Chase | chasej | [email protected] |
Charles Hoover | choover | [email protected] |
Adrian Evans | adevans | [email protected] |
Susan Walter | susan82 | [email protected] |
Stephanie King | stephanieking | [email protected] |
Erika Miller | jessica32 | [email protected] |
In a CSV file that same exact data would be rendered like this:
users.csv
Name,Username,Email Roger Smith,rsmith,[email protected] Michelle Beck,mlbeck,[email protected] Ashley Barker,a_bark_x,[email protected] Lynn Gonzales,goodmanjames,[email protected] Jennifer Chase,chasej,[email protected] Charles Hoover,choover,[email protected] Adrian Evans,adevans,a[email protected] Susan Walter,susan82,[email protected] Stephanie King,stephanieking,[email protected] Erika Miller,jessica32,[email protected]
Notice that the first row of the CSV file doesn’t actually represent any data, just the labels of the data that’s present in the rest of the file. The rest of the rows of the file are the same as the rows in the spreadsheet software, just instead of being separated into different cells they’re separated by… well I suppose it’s fair to say they’re separated by commas.
Instructions
CSV files are just plain text files!
Open logger.csv
using our standard with
syntax, saving the file object in the temporary variable log_csv_file
.
Print out the contents of logger.csv
by calling .read()
on the file. Notice that it is parsed as a string.