python每日一练之I/O实现读写csv文件

CSV:以纯文本形式存储数据,由任意数目的记录组成,记录之间以某种字符分隔

1.写文件

def write_csv():
    list1 = [[1, 2, 3], [4, 5, 6]]
    header = [0, 0, 0]
    l2 = [7, 8, 9]
    # utf-8-sig 此种格式可以用excel打开;newline如果不写明,每次write后,会自动增加新行。
    with open('csv3.csv', 'w', encoding='utf-8-sig', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(header)  # 写入一行
        writer.writerows(list1)
        writer.writerow(l2)

2.读取文件

如果不加编码格式,这里会报错:'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence 可以声明忽略编码错误:errors='ignore'的,但是读出来的数据会有乱码。

def read_csv():
    with open('csv3.csv', 'r', encoding='utf-8-sig') as f:
        reader = csv.reader(f)
        header = next(reader)  # 获取行头
        print(header)
        for r1 in reader:
            print(r1)

3.写入字典

def write_dict():
    header = ['name', 'sex']
    dict1 = {'name': "test", 'sex': 18}

    with open('csv4.csv', 'w', encoding='utf-8-sig', newline='') as f:
        writer = csv.DictWriter(f, header)  # 需要标题,如果没有会报错__init__() missing 1 required positional argument: 'fieldnames'
        writer.writeheader()
        writer.writerow(dict1)  # 可以写入单行或者多行 rows

4. 读取字典

def read_dict():
    with open('csv4.csv', 'r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        # 无需读取标题
        for row in reader:  # 每次读取一行,返回一个dict
            print(row['name'], row['sex'])

 

上一篇:python 类型注解


下一篇:【搜索】【动态规划】【杂题】——洛谷P1514.引水入城