csv模块
# 写csv文件 import csv with open('test1.csv', 'a+',newline='') as f: #a+ writer = csv.writer(f) writer.writerow([0,'11']) #写一行 someiterable=[[11,22],[33,44]] #写多行 writer.writerows(someiterable)
# 读取csv文件 import csv with open('test1.csv', 'r') as f: reader = csv.reader(f) for row in reader: # do something with row, such as row[0],row[1] print(row)
# 写csv文件-字典方式 import csv with open('test1.csv', 'w') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) #fieldnames列名 writer.writeheader() writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
# 读取csv文件-字典方式 import csv with open('test1.csv', 'r') as f: reader = csv.DictReader(f) for row in reader: # do something with row, such as row[0],row[1] print(row['first_name'], row['last_name']) #first_name、last_name列名
天道酬勤 循序渐进 技压群雄