Categories
Python Answers

How to read and write CSV files with Python?

Spread the love

Sometimes, we want to read and write CSV files with Python.

In this article, we’ll look at how to read and write CSV files with Python.

How to read and write CSV files with Python?

To read and write CSV files with Python, we can use the csv module.

For instance, we can write database to a csv file with

data = [
    (1, "A towel,", 1.0),
    (42, " it says, ", 2.0),
    (1337, "is about the most ", -1),
]


with open("test.csv", "wt") as fp:
    writer = csv.writer(fp, delimiter=",")
    writer.writerows(data)

to call open to open a csv file to write to.

And then we call csv.write to get a writer object.

And then we call writerows with data to write the tuples into their own rows.

To read csv files, we write

with open("test.csv") as fp:
    reader = csv.reader(fp, delimiter=",", quotechar='"')
    data_read = [row for row in reader]

to call csv.reader with the csv file fp to get the reader object.

And then we use list comprehension to turn the rows from reader into a list.

Conclusion

To read and write CSV files with Python, we can use the csv module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *