1

我的问题是,在 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()
4

3 回答 3

6

Python 是强类型的。

elif n == '2':
于 2012-04-05T05:47:21.887 回答
3

它正在阅读您的输入。只是当你读过一次文件时,你就完成了;下次您对其进行迭代时,该文件不会神奇地从头开始再次读取。所以你的for line in file:作品一次又一次,因为结束后文件中没有任何内容!要解决此问题,只需将其放在函数file.seek(0)的末尾即可;list_teams()这会将文件重置为开头。

可能还有其他问题(Ignacio 发现了一个错误并且还有其他优化要进行)但这可能是您的直接问题。

于 2012-04-05T06:03:55.157 回答
0

You might take a re-look of code to make it more Pythonic, reduce redundancy and add readability

First Your repetitive code block which you can easily overcome by using list or dictionary or named tuples, just an example with 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

Now the second part. Instead of using find and then indexing, you can simply use 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

And finally it seems, multiple calls to list_teams would fail, as because you are reacing the end. One solution would be

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

Alternatively you can always seek to the beginning before reading the file.

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
于 2012-04-05T06:05:54.813 回答