Python - writing and reading csv files

1.csv file introduction

CSV file is a common data format, which separates different fields with commas, and each line represents a data record. In Python, we can use the csv module to read and write CSV files.

2. Write CSV file

In Python, we can use the writer object of the csv module to write CSV files. Below is an example:

import csv

# 创建要写入的数据
data = [
    ['张三', 20, '男'],
    ['李四', 25, '女'],
    ['王五', 30, '男']
]

# 打开文件,指定写入模式
with open('data.csv', 'w', newline='') as file:
    # 创建csv写入对象
    writer = csv.writer(file)
    # 写入表头
    writer.writerow(['姓名', '年龄', '性别'])
    # 写入数据
    writer.writerows(data)

In the above example, we first created the data to be written, which is a list containing multiple lists. Then use open()the function to open the file and specify the write mode. newline=''Indicates that no extra newlines are used. Then create a csv write object writer, use writerow()the method to write the header, and use writerows()the method to write the data. Finally, use withthe statement to automatically close the file.

It should be noted that when writing to a CSV file, the data needs to be converted into a string format. If the written data contains special characters such as commas and double quotes, it needs to be processed. For example:

import csv

# 创建要写入的数据
data = [
    ['张三', 20, '男'],
    ['李四', 25, '女'],
    ['王五', 30, '男'],
    ['"Tom, Jerry"', 35, '男']
]

# 打开文件,指定写入模式
with open('data.csv', 'w', newline='') as file:
    # 创建csv写入对象
    writer = csv.writer(file)
    # 写入表头
    writer.writerow(['姓名', '年龄', '性别'])
    # 写入数据
    for row in data:
        # 将包含特殊字符的数据进行处理
        row[0] = row[0].replace('"', '""')
        row[0] = f'"{row[0]}"'
        writer.writerow(row)

In the above example, we have created a data containing special characters, it contains comma and double quotes. In order to write this data, we need to escape the double quotes and put double quotes around the data. Specifically, we use replace()the method to replace a double quote with two double quotes, and then use the method f-stringto enclose the data in double quotes.

3. Read the CSV file

In Python, we can use the reader object of the csv module to read CSV files. Below is an example:

import csv

# 打开文件,指定读取模式
with open('data.csv', 'r') as file:
    # 创建csv读取对象
    reader = csv.reader(file)
    # 遍历每一行数据
    for row in reader:
        print(row)

In the above example, we use open()the function to open the file and specify the read mode. Then create a csv read object reader, use fora loop to traverse each row of data, and use print()the function to output.

It should be noted that when reading CSV files, each row of data will be parsed into a list. If there is a header in the CSV file, the first line of data is the header, and you can use next()the function to skip it:

import csv

# 打开文件,指定读取模式
with open('data.csv', 'r') as file:
    # 创建csv读取对象
    reader = csv.reader(file)
    # 跳过表头
    next(reader)
    # 遍历每一行数据
    for row in reader:
        print(row)

In the above example, we used next()the function to skip the table header.

In addition, if the CSV file contains special characters, such as commas, double quotation marks, etc., you need to use csv.readerthe quotecharparameter to specify the escape character. For example:

import csv

# 打开文件,指定读取模式
with open('data.csv', 'r') as file:
    # 创建csv读取对象
    reader = csv.reader(file, quotechar='"')
    # 遍历每一行数据
    for row in reader:
        print(row)

In the above example, we use quotechar='"'to specify double quotes as escape characters. This way, data containing double quotes can be parsed correctly.

Guess you like

Origin blog.csdn.net/qq_48892708/article/details/129768533