Python 读取文件带空白

Python 读取文件带空白,python,Python,通过CorePytho工作 我可以使用下面的代码打印文件,w/eachLine, 如果我去掉逗号,它的行距是双倍的 我正在尝试使用逗号来去除whiteaspace w/o-不需要寻找答案,因为下面的代码只打印.txt的最后一行,而不打印前面的几行 #! /usr/bin/env python 'readTextFile.py == read and display a text file' #get the filename fname = raw_input('Enter the file

通过CorePytho工作 我可以使用下面的代码打印文件,w/eachLine, 如果我去掉逗号,它的行距是双倍的

我正在尝试使用逗号来去除whiteaspace w/o-不需要寻找答案,因为下面的代码只打印.txt的最后一行,而不打印前面的几行

#! /usr/bin/env python

'readTextFile.py == read and display a text file'

#get the filename
fname = raw_input('Enter the filename: ')
print

#attempt to open the file for reading
try:
    fobj = open(fname, 'r')
except IOError, e:
    print "*** file open error:", e
else:
    #display contents to the screen
    for eachLine in fobj:
        x = [fname.rstrip('\n') for eachLine in fobj]
        print eachLine,
    fobj.close()

您正在读取循环中的文件上循环。Python文件对象具有“读取位置”;每次迭代文件对象时,读取位置都会移动到下一行

因此,在fobj循环中的
for eachLine中,您再次使用列表遍历
fobj

实际上,您只读取第一行,然后将文件的其余部分(无换行符)存储在
x
中。在Python2中,在列表理解循环中重用的
eachLine
变量与在外部
for
循环中使用的变量相同,因此最终它仍然绑定到文件中的最后一行。(在Python 3中,列表理解有自己的作用域,因此列表理解中的
eachLine
变量是独立的,就像另一个函数中的局部变量一样)

如果只想从当前行中删除换行符,请执行以下操作:

eachLine = eachLine.rstrip('\n')

并将文件的其余部分留在
for
循环的后续迭代中处理。

它正在打印文件中的最后一行文本。那么它一定在读它?还是我完全疯了。@ScottParkis:啊,Python 2;列表中的
eachLine
变量泄漏,并绑定到最后一行。谢谢-我对Python所知甚少,每次我陷入困境时,答案都比我想象的简单。