-1
通过CorePytho工作 我可以使用下面的代码打印一个文件w/eachLine, 如果我删除逗号它是双倍间隔。阅读文件条空白
我想使用逗号去掉空白的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()
它正在打印文件中的最后一行文本。所以它一定是在读它?或者我完全不在。 – scopa 2014-10-06 14:43:42
@ScottParkis:啊,Python 2;列表理解中的'eachLine'变量泄漏并且被绑定到最后一行。 – 2014-10-06 14:45:15
谢谢 - 我对Python的了解很少,每次遇到困难时,答案都比我想象的要简单。 – scopa 2014-10-06 14:48:24