import csv
# 读取字符串
for row in csv.reader(['one,two,three']):
print(row) # ['one', 'two', 'three']
# 写数据
with open('test_csv_data.csv', 'w', newline='') as f:
writer = csv.writer(f, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['My name is','Tom', 'Bob', 'Jim', 'May'])
writer.writerow(['Color is', 'red', 'yellow green','blue'])
# 读数据
with open('test_csv_data.csv', newline='') as f:
spamreader = csv.reader(f, delimiter=' ', quotechar='|')
for row in spamreader:
print(', '.join(row))
# My name is, Tom, Bob, Jim, May
# Color is, red, yellow green, blue
# 写入csv文件 writer.writerow和writer.writerows
with open('csv_test1.csv', 'w', newline='') as f: # 如不指定newline='',有时则每写入一行,将有一空行被写入
writer = csv.writer(f)
writer.writerow(['name', 'age', 'tel']) # 写入一行用writerow
with open('csv_test2.csv', 'w', newline='') as f: # 如不指定newline='',有时则每写入一行,将有一空行被写入
writer = csv.writer(f)
data = [('Tom', '25', '1367890900'), ('Jim', '18', '1367890800')]
writer.writerows(data) # 多行用writerows
#
# 读取csv文件
with open('csv_test1.csv', encoding='utf-8') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
print(row)
with open('csv_test2.csv', encoding='utf-8') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
print(row)
# ['name', 'age', 'tel']
# ['Tom', '25', '1367890900']
# ['Jim', '18', '1367890800']
# 以字典方式写入csv 并读取csv
datas = [{'name': 'Bob', 'age': 23}, {'name': 'Jerry', 'age': 44}, {'name': 'Tom', 'age': 15}]
## 以字典方式写入csv
with open('test_csv_data.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, ['name', 'age']) # 标头在这里传入,作为第一行数据
writer.writeheader()
for row in datas:
writer.writerow(row)
# 还可以写入多行
writer.writerows(datas)
## 以字典方式读取csv
with open('test_csv_data.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'], row['age'])
# name age
# Bob 23
# Jerry 44
# Tom 15
# Bob 23
# Jerry 44
# Tom 15
# 捕获和报告错误:
import csv, sys
filename = 'test_csv_data.csv'
with open(filename, newline='') as f:
reader = csv.reader(f)
try:
for row in reader:
print(row)
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
python之csv模块学习
最新推荐文章于 2021-11-25 22:53:27 发布