我试图使用csv模块整齐地导入两个文件。第一个(books.txt)似乎整齐地导入到列表中。第二位要求将其插入dict中。我已经尝试了我在网上找到的各种解决方案,但无法按照自己的意愿使用它。它应该遍历文本文件,line1应该是键,line2是值,line3是第二个键,依此类推
import csv
def importer():
with open('books.txt', newline='') as inputfile:
reader = csv.reader(inputfile)
books = list((row) for row in reader)
print(books)
with open('ratings.txt', newline='') as inputfile:
reader = csv.reader(inputfile)
ratings = list((row) for row in reader)
print(ratings)
importer()
源.txt文件和完整代码在此处可见
https://repl.it/@glasgowm1498/CoralTangibleWamp
重写之前我的代码如下:
ratings = {}
with open('ratings.txt', 'r') as f:
while True:
name = f.readline().strip()
values = f.readline().strip().split()
if not name:
break
else:
ratings[name] = list(int(i) for i in values)
答案 0 :(得分:0)
也许这会对你有所帮助:
('Ben', ['5', '0', '0', '0', '0', '0', '0', '1', '0', '1', '-3', '5', '0',
'0', '0', '5', '5', '0', '0', '0', '0', '5', '0', '0', '0', '0',
'0', '0', '0', '0', '1', '3', '0', '1', '0', '-5', '0', '0', '5',
'5', '0', '5', '5', '5', '0', '5', '5', '0', '0', '0', '5', '5',
'5', '5', '-5'])
('Moose', ['5', '5', '0', '0', '0', '0', '3', '0', '0', '1', '0', '5', '3',
'0', '5', '0', '3', '3', '5', '0', '0', '0', '0', '0', '5', '0',
'0', '0', '0', '0', '3', '5', '0', '0', '0', '0', '0', '5', '-3',
'0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '5', '5', '0',
'3', '0', '0'])
('Reuven', ['5', '-5', '0', '0', '0', '0', '-3', '-5', '0', '1', '-5', '5',
'0', '1', '0', '1', '-3', '1', '-5', '0', '0', '0', '0', '0',
'0', '3', ... etc ... ]
输出(裁剪):
{{1}}