I have a file example.csv
with the contents
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3
How do I read this example.csv
with Python?
Similarly, if I have
data = [(1, "A towel,", 1.0),
(42, " it says, ", 2.0),
(1337, "is about the most ", -1),
(0, "massively useful thing ", 123),
(-2, "an interstellar hitchhiker can have.", 3)]
How do I write data
to a CSV file with Python?
Here are some minimal complete examples how to read CSV files and how to write CSV files with Python.
Python 2+3: Reading a CSV file
Pure Python
After that, the contents of
data_read
areUnicode and Python 2.X
If you want to write Unicode, you have to install
unicodecsv
. Do not open the file withcodecs.open
but simply withopen
. Write it withRelated
mpu
Have a look at my utility package
mpu
for a super simple and easy to remember one:Pandas
See
read_csv
docs for more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.If you haven't heard of Seaborn, I recommend having a look at it.
Other
Reading CSV files is supported by a bunch of other libraries, for example:
dask.dataframe.read_csv
spark.read.csv
Created CSV file
Common file endings
.csv
Working with the data
After reading the CSV file to a list of tuples / dicts or a Pandas dataframe, it is simply working with this kind of data. Nothing CSV specific.
Alternatives
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
Writing a CSV file
First you need to import csv
For eg: