csv文件读:
import csv
from collections import namedtuple
def read():
with open('produ.csv', encoding='utf-8-sig') as f:
reader = csv.reader(f)
headers = next(reader)
print(headers)
for row in reader:
print(row)
def csv_read_by_nametuple():
with open('produ.csv', encoding='utf-8-sig') as f:
reader = csv.reader(f)
headers = next(reader)
Row = namedtuple('Row', headers)
for i in reader:
row = Row(*i)
print(row)
print(type(row))
print('{}->{}->{}'.format(row.product, row.name, row.price))
def csv_read_by_dict():
with open('produ.csv', encoding='utf-8-sig') as f:
reader = csv.DictReader(f)
headers = next(reader)
print(headers)
for i in reader:
print(i)
print(type(i))
if __name__ == '__main__':
csv_read_by_dict()
csv文件写:
import csv
def csv_write():
"写入文件"
headers = ['编号', '课程', '讲师']
rows = [
(1, 'Python', 'Eason'),
(2, 'C', 'dfe'),
(3, 'fe', 'def')
]
with open('mycorse.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
print(writer)
print(type(writer))
writer.writerow(headers)
writer.writerows(rows)
def csv_write_dict():
headers = ['ID', 'Title']
rows = [
{'ID': 1, 'Title': 'org'},
{'ID': 2, 'Title': 'org'},
{'ID': 3, 'Title': 'org'},
{'ID': 4, 'Title': 'org'},
]
with open('myco.csv', 'w', encoding='utf-8',newline='')as f:
writer = csv.DictWriter(f, headers)
writer.writeheader()
writer.writerows(rows)
if __name__ == '__main__':
csv_write_dict()