'''
如果文件读取数据出错,可以考虑加一个encoding属性,取值可以是:utf-8,gbk,gb18030
或者加一个属性error,取值为ignore,例如
open(path, encoding='gb18030', errors='ignore')
'''
'''
1.csv数据为:
1,2,3
4,5,6
7,8,9 '''
import csv
def read_file1():
with open('1.csv','r') as fp:
# reader相当于一个迭代器
reader = csv.reader(fp)
# 使用next,那么就相当于把指针fp向下移动一行
next(reader)
for read in reader:
print(read) def read_file2():
with open('1.csv','r') as fp:
# 将csv的数据转化为字典,这个时候reader里面就不再包含第一行数据
reader = csv.DictReader(fp)
for read in reader:
print(read['2']) read_file1()
'''
输出:
['4', '5', '6']
['7', '8', '9']
'''
read_file2()
'''
输出:
5
8
''' def write_file1():
header = ['user', 'age']
values = [
('张三', '12'),
('李四', '13')
]
# newline默认为'\n',意思就是每写入一条数据就会多一个换行
# 如果这里编码出错,可以指定encoding的值
with open('2.csv','w',newline='') as fp:
writer = csv.writer(fp)
writer.writerow(header)
writer.writerows(values) write_file1() def write_file2():
header = ['user', 'age']
values = [
{'user':'张三','age': '12'},
{'user':'李四','age':'13'}
]
# newline默认为'\n',意思就是每写入一条数据就会多一个换行
# 如果这里编码出错,可以指定encoding的值
with open('2.csv','w',newline='') as fp:
writer = csv.DictWriter(fp,header)
# 写入字典头
writer.writeheader()
# 将字典数据写入
writer.writerows(values) write_file2() '''
两个函数执行后的结果一样,文件2.csv中数据为:
user,age
张三,12
李四,13 '''