python3操作csv文件的代码,包含创建、读写等操作

2022-05-03 00:00:00 操作 读写 包含

本文详细演示了Python3操作csv文件的方法,包括初始化csv数据、读取和写入csv文件等常规操作。

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/4
功能描述:python3操作csv文件的代码,包含创建、读写等操作
"""
import csv
import datetime

# 数据
data = [
    [1, "pidancode.com", 100, datetime.datetime(2022, 3, 17)],
    [2, "bandao.cn", 200, datetime.datetime(2004, 4, 27)],
    [3, 'baidu.com', 300, datetime.datetime(2006, 7, 14)],
    [4, "google.com", 400, datetime.datetime(1999, 1, 9)],
]

# 自己创建dialect
csv.register_dialect(
    "dialect",
    delimiter=',',              # 字段分隔符
    escapechar='\\',            # 转义字符
    quotechar='"',              # 包裹字符
    doublequote=False,          # 使转义字符生效
    lineterminator='\n',        # 行与行之间的分隔符
    quoting=csv.QUOTE_ALL       # 包裹模式
)

csv_file = 'pidancode.com.csv'

# 写文件
with open(csv_file, "w") as file:
    writer = csv.writer(file, dialect="dialect")
    for item in data:
        writer.writerow(item)

# 读文件
with open(csv_file, "r") as file:
    reader = csv.reader(file, dialect="excel")
    for item in reader:
        print(item)

# 读文件
with open(csv_file, "r") as file:
    reader = csv.DictReader(file, fieldnames=["No", "domain", "point", "datetime"], dialect="excel")
    data = [item for item in reader]
    print(data)

# 写文件
with open(csv_file, "w") as file:
    writer = csv.DictWriter(file, fieldnames=["No", "domain", "point", "datetime"], dialect="excel")
    writer.writeheader()
    for item in data:
        writer.writerow(item)

相关文章