Python教程

python CSV操作

本文主要是介绍python CSV操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

来源:(47条消息) python_csv文件写入_侯小啾的博客-CSDN博客_pythoncsv文件写入

使用writerow方法给csv文件写入内容。
open()函数如果没有设定 newline=’’ (空字符串),表格中会隔一行写一行。
然后创建一个writer对象。writerow()方法可以写入一行,writerows()方法可以写入多行。

writerow()
import csv


persons = [('Tom', 20, 180), ('Allen', 21, 182), ('Jerry', 22, 181)]
headers = ('name', 'age', 'height')
with open('persons.csv', 'w', encoding='utf-8', newline='') as f:
write = csv.writer(f) # 创建writer对象
write.writerow(headers)
# 写内容,writerrow 一次只写入一行
for data in persons:
write.writerow(data)


writerows()
一次性写入多行,不用遍历。

persons = [('Tom', 20, 180), ('Allen', 21, 182), ('Jerry', 22, 181)]
headers = ('name', 'age', 'height')
with open('persons2.csv', 'w', encoding='utf-8', newline='') as f:
write = csv.writer(f)
write.writerow(headers)
# 写内容,writerows,一次写入多行内容
write.writerows(persons)


DictReader()
写入字典数据。

persons = [
{'name': 'Tom', 'age': 20, 'height': 180},
{'name': 'Allen', 'age': 21, 'height': 182},
{'name': 'Jerry', 'age': 22, 'height': 181},
]
# 数据的keys要跟表头对应,数量也要保持一致,否则会报错
headers = ('name', 'age', 'height')
with open('persons3.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, headers)
writer.writeheader()
writer.writerows(persons)
CSV读取
两种方法:

with open('persons.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
print(reader, type(reader)) # <_csv.reader object at 0x000001D5AEF6B518>
for i in reader:
print(i)
程序运行结果:


with open('persons.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
print(reader, type(reader)) # <_csv.reader object at 0x000001D5AEF6B518>
for i in reader:
print(i['age'])
程序运行结果:

这篇关于python CSV操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!