简体   繁体   English

从文件读取时为什么打印新行?

[英]Why new line is printed when I read from file?

When I run this code I see new line. 运行此代码时,我看到换行符。
I resolved it by adding rCourse.split() instead of rCourse . 我通过添加rCourse.split()而不是rCourse解决了它。
But I am still curious about why new line is printed? 但是我仍然很好奇为什么要打印新行?

test.py test.py

f = open('/home/test.txt', 'r')
print "oldCourses are:"
for rCourse in  f:
   print rCourse

test.txt test.txt

course1
course2
course3
adsfgsdg
sdgsfdg
sfbvfsbv
fbf

oldOutput oldOutput

course1

course2

course3

adsfgsdg

sdgsfdg

sfbvfsbv

fbf

fsbf

Because your lines end with the '\\n' character and print adds another '\\n'. 因为您的行以'\\ n'字符结尾,并且print添加了另一个'\\ n'。

There are multiple ways to fix this. 有多种解决方法。 I like to use the Python 3 print function. 我喜欢使用Python 3 print功能。

from __future__ import print_function

f = open('test.txt', 'r')
print("oldCourses are:")
for rCourse in  f:
   print(rCourse, end='')

Suppose you have this text file: 假设您有以下文本文件:

$ cat test.txt
Line 1
Line 2
Line 3
Line 4

If you open that and read and print line-by-line you get two \\n for each line; 如果打开它并逐行读取和打印,则每行将得到两个\\n one that is in each line of the file and one put there by default by print : 文件每一行中的一行,默认情况下通过print放置在其中:

>>> with open("test.txt") as f:
...    for line in f:
...       print line
... 
Line 1

Line 2

Line 3

Line 4

There many ways to manage that. 有很多方法可以解决这个问题。

You can use .rstrip() to remove the \\n : 您可以使用.rstrip()删除\\n

>>> with open("test.txt") as f:
...    for line in f:
...       print line.rstrip()
... 
Line 1
Line 2
Line 3
Line 4

You can use a , to suppress the automatic \\n : 您可以使用,以抑制自动\\n

>>> with open("test.txt") as f:
...    for line in f:
...       print line,
... 
Line 1
Line 2
Line 3
Line 4

In Python 3.x use the print function which can also be imported in Python 2. 在Python 3.x中,使用打印功能 ,该功能也可以在Python 2中导入。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM