Reading and Writing CSV Files with Python
In Python, we can use the built-in csv module to read and write CSV files. A CSV file is a common file format for storing tabular data. Below is a simple example showing how to read a CSV file and write its content to another CSV file.
Example
import
csv
Read the 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 the CSV file
with
open
(
'output.csv'
,
mode
=
'w'
,
newline
=
''
,
encoding
=
'utf-8'
)
as
outfile:
writer
=
csv
.
writer
(
outfile
)
writer.
writerows
(
data
)
Code analysis:
import csv: import Python'scsvmodule, which provides the ability to read and write CSV files.with open('input.csv', mode='r', newline='', encoding='utf-8') as infile:: open the file namedinput.csvin read-only mode with the encodingutf-8。newline=''to ensure newlines are handled correctly on different operating systems.reader = csv.reader(infile): create a CSV reader object to read the file line by line.data = [row for row in reader]: use a list comprehension to store each line of the file in thedatalist.with open('output.csv', mode='w', newline='', encoding='utf-8') as outfile:: open the file namedoutput.csvin read-only mode with the encodingutf-8。writer = csv.writer(outfile): create a CSV writer object to write data to the file.writer.writerows(data): Setdatawrites all rows in the list to theoutput.csvfile.
Output: suppose the input.csv file content is as follows:
Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
After running the code above, theoutput.csv file will contain the same content as input.csv :
Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Python3 Examples