下一行转义字符不工作python

时间:2013-06-24 06:58:15

标签: python macos unix

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

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'更改带有"\n"的单引号,如下所示:

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

我需要的实际输出是:

abc
def
ghi

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

4 个答案:

答案 0 :(得分: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()将整个文件加载到内存中,如果文件大于内存,则无法读取,因此迭代文件。

答案 1 :(得分: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

答案 2 :(得分: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循环或任何其他iterable逐个返回该iterable中的下一个项目,并将其分配给for循环中使用的变量:

for x in lis:  #in each iteration x is assgined the next item from lis
   print x

答案 3 :(得分:0)

with open('source.txt', 'r') as f:
    content = f.read()
    print content
相关问题