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
-1
A
回答
2
我想你错过分裂sentenceInLine
像sentenceInLine.split(' ')
2
你遍历每一行,然后你根据'\n'
分割线。 \ n是换行符。那会混淆你的逻辑。
1
因此,你试图做的事情有点令人困惑,但你应该在用户输入n的值后检查n。不在最后。
你可能想也搭上那里的文件不能被发现,我认为这是你需要什么异常:当用户输入n = 0时,该程序退出
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()
相关问题
- 1. 为什么我的循环早打破?
- 2. 为什么我的代码跳出一个循环在php
- 3. 为什么我的代码被破坏?
- 4. 为什么我的代码的这部分不遵循循环?
- 5. 为什么我的for循环退出?
- 6. 为什么循环迭代超出Integer.MAX_VALUE?
- 7. 为什么添加我的Sql UPDATE会破坏我的循环?
- 8. 为什么“c.execute(...)”会打破循环?
- 9. C#为什么List.Remove()打破'for循环'?
- 10. 为什么for循环不打破
- 11. 为什么我的内循环迭代少于出循环?很奇怪?
- 12. 为什么我的java代码进入无限循环?
- 13. 为什么我的代码在secound while循环中停止?
- 14. 为什么不能在我的代码中停止循环?
- 15. 为什么我的代码循环两次?
- 16. 为什么我的JavaScript代码进入无限循环?
- 17. 为什么我的Python代码跳过一个while循环?
- 18. 为什么我的代码中有无限循环?
- 19. 为什么此代码在循环列表时抛出'InvalidOperationException'?
- 20. 为什么这段代码让我跳出ruby程序的循环?
- 21. 为什么我的循环被破坏?二维数组[20] [6]
- 22. 为什么第二个SQL语句会打破我的循环?
- 23. 代码是无限循环,我不知道为什么
- 24. 即使循环条件仍然有效,为什么我的代码以退出代码退出:0?
- 25. 为什么我的代码抛出ClassNotFoundException?
- 26. 为什么我的代码抛出IllegalMonitorStateException?
- 27. 为什么我必须打破;在这里循环?
- 28. 我的循环出了什么问题
- 29. 为什么代码在jsfiddle中破解
- 30. 为什么ClassName打破这个代码?
原来的问题要求。 – Zfrd 2012-03-29 20:12:23