错误内容:
1.TypeError: __new__() missing 5 required positional arguments: 'ID', 'UserName', 'Password', 'Age', and 'Country'
2.使用列表输出时,每隔一个打印一个空列表
《Python爬虫开发与项目实战》132页
第五章数据储存 5.1.2存储为CSV 例子
书上使用的是python2,小仙女使用的是python3
解决办法:
在写入时加上newline = '',加这个的时候我本意是想输出的时候不换行,结果把这个问题也解决了...
我也不知道为什么,反正能运行了,并得出了想要的结果
要是有谁明白,麻烦告诉一下我,谢谢
import csv from collections import namedtuple # headers = ['ID', 'UserName', 'Password', 'Age', 'Country'] # rows = [(1001,"qiye", 'qiye_pass', 24, 'china'), # (1002, 'Mary', 'Mary_pass', 20 , 'USA'), # (1003, 'Jack', 'Jack_pass', 20, 'USA') # ] # with open ('qiye.csv','w') as f: # f = csv.writer(f) # f.writerow(headers) # f.writerows(rows) #以上为元组 #以下为字典 headers = ['ID', 'UserName', 'Password', 'Age', 'Country'] rows = [{'ID': 1001, 'UserName': "Qiye", 'Password': 'Qiye_pass', 'Age': 24, 'Country': 'China'}, {'ID': 1002, 'UserName': 'Mary', 'Password': 'Mary_pass', 'Age': 20, 'Country': 'USA'}, ] with open ('qiye.csv','w',newline= '') as f:#参数加上newline= '',不换行 f = csv.DictWriter(f, headers) f.writeheader() f.writerows(rows) print('以下使用列表输出') with open('qiye.csv') as f: f = csv.reader(f) headers = next(f) print(headers) for row in f: print(row) print('以下使用命名元组') with open('qiye.csv') as f: f = csv.reader(f) headers = next(f) Row = namedtuple('Row', headers) for r in f: row = Row(*r) print(row.UserName, row.Password) print(row) print('以下读取到一个字典序列') with open('qiye.csv') as f: f = csv.DictReader(f) for row in f: print(row.get('UserName'), row.get('Password'))
运行结果:
以下使用列表输出
['ID', 'UserName', 'Password', 'Age', 'Country']
['1001', 'Qiye', 'Qiye_pass', '24', 'China']
['1002', 'Mary', 'Mary_pass', '20', 'USA']
以下使用命名元组
Qiye Qiye_pass
Row(ID='1001', UserName='Qiye', Password='Qiye_pass', Age='24', Country='China')
Mary Mary_pass
Row(ID='1002', UserName='Mary', Password='Mary_pass', Age='20', Country='USA')
以下读取到一个字典序列
Qiye Qiye_pass
Mary Mary_pass