Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: CSV files
by RS  admin@robinsnyder.com : 1024 x 640


1. CSV files
A CSV (Comma Separated Values) file is often used to store table values in a somewhat portable text format.

CSV files vary as to exact format but some parameters are fairly standard.

A CSV file typical represents a table - a flat database of cells organized into rows and columns. The following are important for a CSV file.

2. Structure
The usual structure of a CSV file is as follows.

3. Import and export
Many programs, such as Excel, have options to import and/or export data in CSV format.

Excel has a Wizard to help with the import. Whenever custom handling of CSV files is required, a language such as Python can be used.

The csv module is required.


4. Example table
Here is the table used for example purposes.


5. Parameters
Some required parameters can be assigned as variables.

Some others are omitted. Defaults used.

6. Write a CSV file
It is best to have prepared a complete table (list of list of cells). If the table is too large, one can construct and write one row at a time.


7. Read CSV as text
To see what is written, the created csv file can be read as text.

The output of the text using quotes is to see what was added by the csv call. In this case, a newline at the end.

8. Read CSV as CSV
The csv file can also be read and processing using the csv module. This is preferred as the delimiters, quotes, etc., are handled automatically.

In this case, the complete table is forced (eager evaluation) so that the file can be closed and processing done elsewhere.

9. Show the CSV table
The CSV file that has been read can now be read as a 2D table - a list of lists of values.


10. Complete program
Here is the Python code [#8]


11. Output
Here is the output of the Python code.


12. CSV as text
Note that csv files are stored and read as text. When it is important that certain data be numeric fields, explicit conversion is necessary.

13. Non-flat files
In relational database terms, a not-flat file or table is a table that has references to other tables.

One way a csv file might represent a pair of tables is as follows.

14. End of page

by RS  admin@robinsnyder.com : 1024 x 640