繁体   English   中英

为什么我的代码“中断”了循环?

[英]why does my code “break” out of loop?

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

我想你错过了像sentenceInLine.split(' ')那样分割sentenceInLine sentenceInLine.split(' ')

您遍历每行,然后根据'\\n'拆分行。 \\ n是换行符。 那会使您的逻辑混乱。

因此,这有点令人困惑,但是您应该在用户输入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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM