0

我使用以下代码逐行读取文本文件并将其打印在屏幕上。

with open("source.txt") as f:
    content = f.readlines()
    print(content)
    print('\n')
f.close()

但是\n只是被附加到输出中,而输出却是一行。例如,如果文件是这样的:

abc
def
ghi

输出是:

['abc\n', 'def\n', 'ghi']

然后我尝试用'\n'with改变单引号,"\n"如下所示:

with open("source.txt") as f:
    content = f.readlines()
    print(content)
    print("\n")
f.close()

我需要的实际输出是:

abc
def
ghi

我能为此做些什么?操作平台:Mac(Unix) 提前致谢。

4

4 回答 4

2

你应该这样做:

with open('source.txt', 'r') as f:
    for line in f: #iterate over lines
        line = line.strip() #removes whitespaces and new lines
        print line #print the line, the print function adds new line

readlines() 将整个文件加载到内存中,如果文件大于内存,则无法读取它,因此遍历文件。

于 2013-06-24T07:02:27.377 回答
1

您可以使用rstrip()

>>> for i in content:
...     print i.rstrip()
... 
abc
def
ghi

您的代码的问题在于它没有按照您的预期执行。content是一个列表,打印列表只会有['abc\n', etc]. 您可以使用 for 循环(如我所示)遍历列表中的每个元素,并在单独的行上单独打印出所有元素。

我不完全确定您为什么拥有print('\n'),但我假设您来自另一种编程语言。Python 会自动添加一个换行符,因此不需要添加一个:)。

最后,rstrip()需要去掉换行符,否则会出现:

>>> for i in L:
...     print i
... 
abc

def

ghi
于 2013-06-24T07:00:40.177 回答
1

问题是您试图打印列表对象本身,而不是您应该遍历列表并打印单个项目:

>>> lis = ['abc\n', 'def\n', 'ghi']
>>> print lis
['abc\n', 'def\n', 'ghi']

print lis 实际上打印列表对象的 str 表示:

>>> print str(lis)
['abc\n', 'def\n', 'ghi']

循环遍历列表并打印单个项目。在 python 中,我们可以循环遍历列表本身,这与需要索引的 C/C++ 不同。

>>> for item in lis:   
...     print item.rstrip('\n')  #removes the trailing '\n'
...     
abc
def
ghi

对列表或任何其他可迭代对象的 for 循环从该可迭代对象中逐一返回下一项,并将其分配给 for 循环中使用的变量:

for x in lis:  #in each iteration x is assgined the next item from lis
   print x
于 2013-06-24T07:10:13.677 回答
0
with open('source.txt', 'r') as f:
    content = f.read()
    print content
于 2013-06-24T09:46:27.747 回答