首先,我有一个名为data的文件夹,该文件夹中的.txt文件是每个美国州的首字母缩略词。这些文件拥有当年和州的最受欢迎的几个名字。随机文件中的几行看起来像这样
AK,F,1910,Mary,14
AK,F,1910,Annie,12
AK,F,1910,Anna,10
AK,F,1910,Margaret,8
AK,F,1910,Helen,7
AK,F,1910,Elsie,6
AK,F,1910,Lucy,6
AK,F,1910,Dorothy,5
AK,F,1911,Mary,12
AK,F,1911,Margaret,7
AK,F,1911,Ruth,7
AK,F,1911,Annie,6
AK,F,1911,Elizabeth,6
AK,F,1911,Helen,6
我的任务是找到用户给出的一系列年份中最受欢迎的名称(性别也由用户提供。正如您所看到的,最流行的名称是第一个带有新年的名称。我的代码如下:
def getTopNames(state, gender, startYear, endYear):
names = []
file = open("data/" + state + ".TXT")
with open(file) as f:
for line in f:
if startYear and gender in line:
names.append(line.split(","))
if startYear < endYear:
startYear += 1
names.append(line.split(","))
print ( lstAll )
这是我得到的错误:
File "C:/Python34/CS1 WORK/top_names.py", line 53, in getTopNames
with open(file) as f:
TypeError: invalid file: <_io.TextIOWrapper name='data/NY.TXT' mode='r' encoding='cp1252'>
我做错了什么?我确保数据文件与我的.py文件所在的文件相同。
答案 0 :(得分:2)
您尝试打开文件两次:
file = open("data/" + state + ".TXT")
with open(file) as f:
应该使用
filename = "data/" + state + ".TXT"
with open(filename) as f:
然后,行
if startYear and gender in line:
不像您认为的那样有效。它实际上意味着
if (startYear) \ # true if startYear is non-zero/nonempty
and (gender in line): # true if the letter M/F occurs *anywhere* in the line
你想要像
这样的东西items = line.split(",")
if str(startYear) in items and gender in items: