Python csv模块读取基本操作

csv即逗号分隔值,可用Excel打开

1.向csv文件中写入数据

(1)列表方式的写入

import csv

with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
    writer = csv.writer(csvfile)

    # 写入一行 
    writer.writerow(['1','2','3','4','5','5','6'])

    # 写入多行
    writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])

(2)字典方式的写入

import csv
with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
    filename = ['first_name','last_name']
    # 写入列标题
    writer = csv.DictWriter(csvfile,fieldnames=filename)
    writer.writeheader()
    writer.writerow({'first_name':'wl','last_name':'wtx'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

2.读取csv文件中的内容

(1)列表方式的读取

import csv
with open(
'data.csv','r',encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: # 读取出的内容是列表格式的 print(row,type(row),row[1])

(2)字典方式的读取

import csv

with open('data.csv','r',encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # 读取的内容是字典格式的
        print(row['last_name'])

猜你喜欢

转载自www.cnblogs.com/wl443587/p/10056083.html