下一行转义字符不工作python



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

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

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

abc
def
ghi

结果是:

['abcn', 'defn', 'ghi']

然后我试着用'n'"n"更改单引号,如下所示:

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

我需要的实际输出是:

abc
def
ghi

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

您应该这样做:

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()将整个文件加载到内存中,如果文件比您的内存大,您就无法读取它,所以对该文件进行迭代。

您可以使用rstrip():

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

你的代码的问题是它没有做你期望它做的事情。content是一个列表,打印列表只需要['abcn', etc]。您可以使用for循环(如我所示)遍历列表中的每个元素,并在单独的一行上单独打印出所有元素。

我不太清楚你为什么有print('n'),但我推测你来自另一种编程语言。Python会自动添加新行,因此不需要添加:)。

最后,需要rstrip()来剥离换行符,否则会出现以下情况:

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

问题是您试图打印列表对象本身,而应该在列表上循环并打印单个项目:

>>> lis = ['abcn', 'defn', 'ghi']
>>> print lis
['abcn', 'defn', 'ghi']

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

>>> print str(lis)
['abcn', 'defn', '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
with open('source.txt', 'r') as f:
    content = f.read()
    print content

最新更新