python for循环迭代
我是python的新手,从我第一次看到它到现在才几个小时。 所以有一个for循环问题: 让我创建一个文件test.txt,其中包含以下文本:python for循环迭代,python,for-loop,Python,For Loop,我是python的新手,从我第一次看到它到现在才几个小时。 所以有一个for循环问题: 让我创建一个文件test.txt,其中包含以下文本: someText # just another line with no text [\n] 让hello.py包含: import sys import os if len(sys.argv) == 2: filename = os.getcwd() f = filename + '/' + sys.argv[1] try:
someText
# just another line with no text [\n]
让hello.py包含:
import sys
import os
if len(sys.argv) == 2:
filename = os.getcwd()
f = filename + '/' + sys.argv[1]
try:
fp = open(f, 'r')
fileList = fp.read().split('\n')
fp.close()
except Exception, e:
print 'raise exception ' + str(e)
if fileList:
for line in fileList:
print ' --> ' + line
在执行hello.py test.txt之后,我得到
--> someText
-->
现在的问题是,在python中迭代到
fileList-1
的方法是什么?或者在我将其放入列表后,在我的test.txt中修剪最后一个转义字符\n
#... your code
for line in fileList:
print ' --> ' + line
作者:
那就行了
否则,您可以执行许多其他技巧,例如:
感谢@Martijin Pieters
的评论:
# Return a list which contain the file lines.
fileList = fp.read().split('\n') -> fileList = fp.read().splitlines()
或:
或:
您可以修改此部件:
#... your code
for line in fileList:
print ' --> ' + line
作者:
那就行了
否则,您可以执行许多其他技巧,例如:
感谢@Martijin Pieters
的评论:
# Return a list which contain the file lines.
fileList = fp.read().split('\n') -> fileList = fp.read().splitlines()
或:
或:
用于文件列表中的行:如果行:
?如果你只是学习Python,你应该使用3.x,我鼓励你完成一个结构化的教程;您已经有一些不好的做法。在不更改其余代码的情况下,只需在read()
之后运行strip()
:fp.read().strip().split('\n')
。但除此之外,我同意Jon的观点,你应该认真阅读基本概念。@poke:或者使用fb.read().splitlines()
@jornsharpe&poke我的代码有什么不好的地方?,对于文件列表中的行:如果行:
?如果你只是学习Python,你应该使用3.x,我鼓励你完成一个结构化的教程;您已经有一些不好的做法。在不更改其余代码的情况下,只需在read()
之后运行strip()
:fp.read().strip().split('\n')
。但除此之外,我同意Jon的观点,你应该认真阅读基本概念。@poke:或者使用fb.read().splitlines()
@jornsharpe&poke我的代码有什么不好的地方?,str.splitlines()
。是的,有很多方法可以做到这一点。我将把它添加到答案中。谢谢。好得多的主意:str.splitlines()
。是的,还有很多方法。我将把它添加到答案中。谢谢
# Remove any `\n` from line you're reading
fileList = fp.read().split('\n') -> fileList = fp.read().rstrip().split('\n')