为什么我的代码“突破”了循环?

时间:2012-03-29 20:09:11

标签: python

fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
f = open(fileName,'r')
numbers = []

for line in f:
    sentenceInLine = line.split('\n')
    for word in sentenceInLine:
          if word != '':
              numbers.append(word)
print numbers
print len(numbers)
print numbers[n-1]

if n == 0:
    print "There is no 0 line"
    break

3 个答案:

答案 0 :(得分:2)

我认为您错过了将sentenceInLine分割为sentenceInLine.split(' ')

答案 1 :(得分:2)

您正在循环每一行,然后根据'\n'拆分行。那个\ n是一个换行符。那会让你的逻辑混淆不清。

答案 2 :(得分:1)

所以你想要做的事情有点令人困惑,但你应该在用户输入n的值后检查n。不在最后。

您可能还希望捕获无法找到文件的异常我认为这就是您所需要的:

fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
if n == 0:
    print "There is no 0 line"
    sys.exit();

try:
    f = open(fileName,'r')
except IOError:
    print "Could not find file"
    sys.exit()