python for循环迭代

时间:2017-05-27 22:22:32

标签: python for-loop

我是python的新手,距离我第一次看到它只有几个小时。 所以有一个循环问题:

让我有一个文件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:
        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
--> 

现在的问题是,在我将fileList - 1放入列表之后,在python中迭代到\n的方法是什么,或者只修剪我test.txt中的最后一个转义字符ALL? / p>

1 个答案:

答案 0 :(得分:0)

您可以修改此部分:

#... your code
for line in fileList:
    print ' --> ' + line

人:

#... your code
for line in fileListe:
    if line:
        print ' --> ' + line

这样就可以了。

否则,您可以执行许多其他技巧,例如:

感谢@Martijin Pieters的评论:

# Return a list which contain the file lines.
fileList = fp.read().split('\n') -> fileList = fp.read().splitlines()

或者:

# Return a list and ignore the last element
fileList = fp.read().split('\n') -> fileList = fp.read().split('\n')[:-1]

或者:

# Remove any `\n` from line you're reading
fileList = fp.read().split('\n') -> fileList = fp.read().rstrip().split('\n')