Read and Write CSV Files with Python

Document 对象参考手册Python3 Examples

In Python, we can use the built-incsvmodule to read and write CSV files. A CSV file is a common file format used to store tabular data. The following is a simple example showing how to read a CSV file and write its contents to another CSV file.

Examples

import csv

# Read CSV file
with open('input.csv', mode='r', newline='', encoding='utf-8') as infile:
    reader = csv.reader(infile)
    data = [row for row in reader]

# Write CSV file
with open('output.csv', mode='w', newline='', encoding='utf-8') as outfile:
    writer = csv.writer(outfile)
    writer.writerows(data)

Code explanation:

  1. import csv: Import Python'scsvmodule, which provides the functionality to read and write CSV files.
  2. with open('input.csv', mode='r', newline='', encoding='utf-8') as infile:: Opens the file namedinput.csvin read-only mode, and specifies the encoding asutf-8。newline='': This is to ensure that newline characters are handled correctly on different operating systems.
  3. reader = csv.reader(infile): Creates a CSV reader object to read the file content line by line.
  4. data = [row for row in reader]: Uses a list comprehension to store each row of data from the file into thedatalist.
  5. with open('output.csv', mode='w', newline='', encoding='utf-8') as outfile:: Opens the file namedoutput.csvin write mode, and specifies the encoding asutf-8。
  6. writer = csv.writer(outfile): Creates a CSV writer object to write data to the file.
  7. writer.writerows(data): Writedataall rows in the list to theoutput.csvfile.

Output: Assumeinput.csvThe file content is as follows:

Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago

After running the above code,output.csvthe file will contain the sameinput.csvcontent as:

Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago

Document 对象参考手册Python3 Examples

Other Extensions