赞
踩
CSV(逗号分隔符)文件是表格与数据库操作之中最常用的输入输出格式。python读取csv文件(reader = csv.reader(f))或写入csv文件(writer = csv.writer(f))是很方便的。
information.csv文件内容如下:
import csv def csv_read(): """csv基本读取""" with open('information.csv', 'r', encoding='utf-8') as f: #经下述操作后,reader成为了一个可以迭代行的文件 reader = csv.reader(f) #先拿出csv文件的首行(一般是基本名称说明的行),此时指针指向下一行 header = next(reader) print(header) for row in reader: print('姓名:{} 住址:{}'.format(row[0], row[3])) ['name', 'age', 'heighth', 'location'] 姓名:a 住址:山东 姓名:b 住址:上海 姓名:c 住址:南京 姓名:d 住址:杭州
上面读取csv的每一行(会输出列表)的特定元素时,需要对列表下标进行索引,需要数出每个下标对应的名称,很麻烦,因此,提出命名元组(namedtuple)的方法,给列表每一个属性都附上他的名称,便于索引。
import csv from collections import namedtuple def csv_reader_by_namedtuple(): """读取csv并用namedtuple映射列名""" with open('information.csv', encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) # 把Row想象成一个类的创建,header列表(命名名称)是类的属性,对应属性值由参数传入 Row = namedtuple('Row', header) for r in reader: # 理解为类的实例化,传入命名值 #row = Row._make(r) row=Row(*r) print(row) print('{}=>{}=>{}'.format(row.name, row.age, row.location)) Row(name='a', age='20', heighth='150', location='山东') a=>20=>山东 Row(name='b', age='15', heighth='180', location='上海') b=>15=>上海 Row(name='c', age='15', heighth='240', location='南京') c=>15=>南京 Row(name='d', age='87', heighth='187', location='杭州') d=>87=>杭州
也可直接采用字典表(csv.DictReader)的方式读取csv文件
def csv_read_by_dict(): """读取键值对到字典表""" with open('information.csv', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: print(row) print('{}=>{}=>{}'.format(row.get('name'), row['age'], row['location'])) OrderedDict([('name', 'a'), ('age', '20'), ('heighth', '150'), ('location', '山东')]) a=>20=>山东 OrderedDict([('name', 'b'), ('age', '15'), ('heighth', '180'), ('location', '上海')]) b=>15=>上海 OrderedDict([('name', 'c'), ('age', '15'), ('heighth', '240'), ('location', '南京')]) c=>15=>南京 OrderedDict([('name', 'd'), ('age', '87'), ('heighth', '187'), ('location', '杭州')]) d=>87=>杭州
1)把元组写入到csv文件
def csv_writer():
"""写入csv文件"""
headers = [("编号", "课程", "讲师")]
rows = [
(1, 'python', 'eason'),
(2, 'C#', 'jeason'),
(3, 'JAVA', 'peason'),
(4, 'c++', 'weason'),
]
with open('my_course.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
# 写入行首
writer.writerows(headers)
#逐行写入
writer.writerows(rows)
2)把字典表写入到csv文件( writer=csv.DictWriter(f,headers))
def csv_writer_dict(): """以字典表方式写入csv""" headers = ['ID', 'Title', 'org', 'url'] rows = [ {'ID': 1, 'Title': 'PYTHON', 'org': 'Youpinketang', 'url': 'http://chengzi.cc'}, {'ID': 1, 'Title': 'PYTHON', 'org': 'Youpinketang', 'url': 'http://chengzi.cc'}, {'ID': 1, 'Title': 'PYTHON', 'org': 'Youpinketang', 'url': 'http://chengzi.cc'}, {'ID': 1, 'Title': 'PYTHON', 'org': 'Youpinketang', 'url': 'http://chengzi.cc'}, dict(ID=5, Title='C#', org='Youpinketang', url='http://chengzi.cc') ] with open('my_course2.csv', 'w', encoding='utf-8', newline='') as f: #writer=csv.DictWriter(f,headers)代表行首为headers writer=csv.DictWriter(f,headers) #写行首 writer.writeheader() writer.writerows(rows)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。