Python3中读取写入csv文件

import csv

# 读取数据
file_path = 'D:\\1csvread.csv'
with open(file_path, encoding='utf-8') as f:
    reader = csv.reader(f)
    result = list(reader)
    # reader()方法返回对象,需要先转型成list才能看到数据 [['1', '小明', '男', '13'], ['2', '小红', '女', '10'], []]
    print(result[0][1])

# 写数据
datas = [
    ['编号', '姓名', '年龄'],
    ['1', '小明', '13'],
    ['2', '小红', '10'],
    ['3', '小青', '15'],
]
with open('1csvwrite.csv', mode='w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    for row in datas:
        writer.writerow(row)

    # newline=''不加的话每写一行空一行
    # 一次写入多行
    # writer.writerows(datas)

 

你可能感兴趣的:(Python,csv)