Home >Backend Development >Python Tutorial >How to Read and Write CSV Files in Python?
To read data from a CSV file, use the Python CSV library. Here's an example:
import csv # Open the CSV file for reading with open("test.csv", "rt") as f: # Create a CSV reader object reader = csv.reader(f, delimiter=",", quotechar='"') # Iterate over the rows in the CSV file for row in reader: print(row)
To write data to a CSV file, also use the Python CSV library:
import csv # Create a list of data to write to the CSV file 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), ] # Open the CSV file for writing with open("test.csv", "wt") as f: # Create a CSV writer object writer = csv.writer(f, delimiter=",", quotechar='"') # Write the data to the CSV file writer.writerows(data)
When working with CSV files:
The following is the output of the example code:
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
The above is the detailed content of How to Read and Write CSV Files in Python?. For more information, please follow other related articles on the PHP Chinese website!