我尝试读取文件,然后将其存储到以年份为关键字的字典中。但是,当我读取文件时,它一次跳过一堆行。该文件包含所有世界系列赛冠军(1903-2014)。
fileName = input("Enter file name: ")
try:
with open(fileName) as f:
for data in f:
data = f.readline().strip("\n")
print(data) ##used to test to make sure the data is being read
except:
print("file doesnt exist")
运行后的输出:
1905,New York Giants
1907,Chicago Cubs
1909,Pittsburgh Pirates
1911,Philadelphia Athletics
1913,Philadelphia Athletics
1915,Boston Red Sox
1917,Chicago White Sox
...
文件
1903,Boston Americans
1905,New York Giants
1906,Chicago White Sox
1907,Chicago Cubs
1908,Chicago Cubs
1909,Pittsburgh Pirates
答案 0 :(得分:5)
for data in f:
已遍历每一行,这意味着:
data = f.readline().strip("\n")
不仅是多余的,它将跳过一行并将data
设置为等于下一行的任何内容。把那条线拿出来
答案 1 :(得分:0)
print dict(x.split(",") for x in open("filename.txt"))
全部是
答案 2 :(得分:0)
执行此操作的最佳方法是使用csv
模块
import csv
fileName = input("Enter file name: ")
with open(fileName) as f:
reader = csv.reader(f)
print(dict(reader))