Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Reading and Writing CSV Files with Python

Reading and Writing CSV Files with Python

Document Object Reference Manual Python3 Examples

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:

  1. import csv: import Python's csv module, which provides the ability to read and write CSV files.
  2. with open('input.csv', mode='r', newline='', encoding='utf-8') as infile:: open the file named input.csv in read-only mode with the encoding utf-8。newline='' to ensure newlines are handled correctly on different operating systems.
  3. reader = csv.reader(infile): create a CSV reader object to read the file line by line.
  4. data = [row for row in reader]: use a list comprehension to store each line of the file in the data list.
  5. with open('output.csv', mode='w', newline='', encoding='utf-8') as outfile:: open the file named output.csv in read-only mode with the encoding utf-8。
  6. writer = csv.writer(outfile): create a CSV writer object to write data to the file.
  7. writer.writerows(data): Set data writes all rows in the list to the output.csv file.

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

Document Object Reference Manual Python3 Examples