Data reading and writing: Python reads and writes CSV files

1. Read the CSV file

csv.reader()

The function of this method is equivalent to ','splitting the data in csv format, and storing each row of split data into a list, and also removing spaces, newlines, tabs, etc. at the end of the data generated by the last split of each row .

import csv
with open('data.csv',mode='r',encoding='utf-8-sig',newline='') as File:
    # 使用csv.reader()将文件中的每行数据读入到一个列表中
    reader = csv.reader(File, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL)
    # 遍历列表将数据按行输出
    for row in reader:
        print(row)            

insert image description here

Access the column elements of each row of data directly through the index

for row in reader:
    print(row[0])

insert image description here

csv.DictReader()

This method saves each row of data in the file in an OrderedDict. This data type is similar to a list of nested tuples. The first element in each tuple is the key, and the second element is the value. The tuple The keys in come from the header information in the CSV data.

import csv
results = []
with open('data.csv',mode='r',encoding='utf-8-sig',newline='') as File:
    reader = csv.DictReader(File)
    for row in reader:
        print(row)

insert image description here

Read some information by key value

    for row in reader:
        print(row['MakeSpan'],row['WaitTime'])

insert image description here

More content about DictReader() has not been learned yet, if necessary, please refer to other articles: CSV.DictReader() method

2. Write to CSV file

  1. First, you need to import the packages needed to read and write csv:
import csv
  1. Use the open() function to open a file, and the parameters commonly used in the open() function:

    file: file path, file name

    mode: open mode, r (read-only), w (write-only), a (append mode)

    newline: whether there is a blank line between each line, there is a blank line by default, ' ': no blank line.

myFile = open('example2.csv', 'w', newline='')
  1. csv.writer module for writing data to CSV:

    csvfile: This can be write()any object with methods.
    dialect='excel': An optional parameter to define a set of parameters specific to a particular CSV.
    fmtparam: Optional parameter that can be used to override existing formatting parameters.

writer = csv.writer(myFile)
  1. Use writerow() and writerows() to write data to a CSV file:

    writerow(): Store the data in a row in the csv file, each element occupies a cell

    writerows(): Save each list in the data to a row in the CSV file, and each element in the list occupies a cell

myData1 = [["这", "是", "writerow", "的", "效", "果"],
           ["这", "是", "writerow", "的", "效", "果"],
           ["这", "是", "writerow", "的", "效", "果"]]
           
myData2 = [["这", "是", "writerows", "的", "效", "果"],
           ["这", "是", "writerows", "的", "效", "果"],
           ["这", "是", "writerows", "的", "效", "果"]]

myFile = open('example2.csv', 'w', newline='')
with myFile:
    writer = csv.writer(myFile)
    
    writer.writerow(myData1) 
    writer.writerows(myData2) 

The effect after writing to the file is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/qq_33021529/article/details/125467793