我的问题是,在python首次读取原始输入后,它随后不再正确读取输入。我已经尝试了很多东西,但我似乎无法得到它。我做错了什么?
file_path = 'C:\\Users\\Neo\\My Documents\\Python Scripts\\FTC Scouting\\sample.txt'
file = open(file_path, 'r')
Team_Numbers = []
tNum = 'Team Number: '
tName = 'Name: '
ui = ''
def list_teams(n):
count = 0
if n == '1':
for line in file:
check = line.find(tNum)
if not check == -1:
print line[len(tNum):] #prints everything after the Team Number:
count += 1
elif n == 2:
for line in file:
check = line.find(tName)
if not check == -1:
print line[len(tName):] #prints everything after the Team Number:
count += 1
while not ui == 'end':
ui = raw_input('1: to list Team Numbers\n2: to list Names\n')
list_teams(ui)
file.close()
答案 0 :(得分:6)
Python是强类型的。
elif n == '2':
答案 1 :(得分:3)
正在阅读输入。只是当你读过一次文件时,你就完成了;下次迭代时,文件不会从一开始就神奇地开始读取。所以你的for line in file:
工作一次,然后再不起作用,因为文件结尾后没有任何内容!要解决此问题,只需将file.seek(0)
放在list_teams()
函数的末尾即可;这会将文件重置为开头。
也可能存在其他问题(Ignacio发现了一个错误并且还有其他优化措施)但这可能是您的直接问题。
答案 2 :(得分:0)
您可以重新查看代码,使其更具Pythonic,减少冗余并增加可读性
首先使用list
或字典或命名元组轻松克服的重复代码块,只是list
keys = ['Team Number: ', 'Name: ']
def list_teams(n):
count = 0
try:
for line in file:
check = line.find(keys[n])
if not check == -1:
print line[len(keys[n]):] #prints everything after the Team Number:
count += 1
except IndexError:
None #Or Any appropriate Error Checking
现在是第二部分。您只需使用string.partition
keys = ['Team Number: ', 'Name: ']
def list_teams(n):
count = 0
try:
for line in file:
print line.partition(keys[n])[2]
count += 1
except IndexError:
None #Or Any appropriate Error Checking
最后看来,对list_teams的多次调用都会失败,因为你正在重新结束。一种解决方案是
keys = ['Team Number: ', 'Name: ']
def list_teams(n):
count = 0
with open(file_path,'r') as f:
try:
for line in file:
print line.partition(keys[n])[2]
count += 1
except IndexError:
None #Or Any appropriate Error Checking
或者,您可以在阅读文件之前始终寻找开头。
keys = ['Team Number: ', 'Name: ']
def list_teams(n):
file.seek(0)
count = 0
try:
for line in file:
print line.partition(keys[n])[2]
count += 1
except IndexError:
None #Or Any appropriate Error Checking