Read and Write CSV Files with Python
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)
# 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:
import csv: Import Python'scsvmodule, which provides the functionality to read and write CSV files.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.reader = csv.reader(infile): Creates a CSV reader object to read the file content line by line.data = [row for row in reader]: Uses a list comprehension to store each row of data from the file into thedatalist.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。writer = csv.writer(outfile): Creates a CSV writer object to write data to the file.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,ChicagoOther Extensions
Python3 Examples