SoFunction
Updated on 2024-11-15

Python csv file read and write operations example details

This article introduces the Python csv file read and write operations examples, the text of the sample code through the introduction of the very detailed, for everyone's learning or work has a certain reference value of learning, the need for friends can refer to the following

python has a built-in csv module with which you can easily manipulate csv files.

1. Writing documents

(1) Method I of writing documents

import csv

# open There are several modes to open a file, here are the four common ones
# r: read data, default mode
# w: write data, if there is already data then it will be cleared first
# a: appending data to the end of the file
# x : write data, fails if file already exists
# Modes 2 through 4 create an empty file first if the file specified by the first parameter does not exist
with open('', 'w', newline='') as f:  
  head = ['Title column 1', 'Title column 2']
  rows = [
        ['Zhang San', 80],
        ['Li Si', 90]
      ] 
  writer = (f) 
  # Write a line of data
  (head) 
  # Write multiple rows of data
  (rows)

(2) Write file method two

import csv
with open('', 'w', newline='') as f:  
  head = ['Title column 1', 'Title column 2']
  rows = [
        {'Title column 1': 'Zhang San', 'Title column 2' :80},
        {'Title column 1': 'Li Si', 'Title column 2' :90}
      ]
  writer = (f,head)
  ()
  (rows)

2. Read the document

Read the file as created above as an example

import csv
with open('') as f:  
  reader = (f)
  for row in reader:
    print(row)

Run results:

['Title column 1', 'Title column 2']
['Zhang San', '80']
['Li Si', '90']

This is the whole content of this article.