Home >Backend Development >Python Tutorial >How to Read and Write CSV Files in Python?

How to Read and Write CSV Files in Python?

DDD
DDDOriginal
2024-12-21 13:11:10931browse

How to Read and Write CSV Files in Python?

How to Read and Write CSV Files

Reading CSV Files

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)

Writing CSV Files

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)

Considerations

When working with CSV files:

  • Python reads CSV files only as strings. Convert to the desired column types manually.
  • Use pandas for advanced data manipulation and visualization.
  • Consider alternative data formats like JSON, YAML, or pickle.

Created CSV File

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn