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

2024-09-27 21:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个代码时,我看到了新的行。
我通过添加rCourse.split()而不是rCourse来解决它。
但我还是很好奇为什么要印新行?你知道吗

你知道吗测试.py你知道吗

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

你知道吗测试.txt你知道吗

course1
course2
course3
adsfgsdg
sdgsfdg
sfbvfsbv
fbf

旧输出

course1

course2

course3

adsfgsdg

sdgsfdg

sfbvfsbv

fbf

fsbf

Tags: 代码pytxthomeopensplitprintcourse2
2条回答

因为您的行以'\n'字符结尾,print添加另一个'\n'。你知道吗

有多种方法可以解决这个问题。我喜欢使用python3print函数。你知道吗

from __future__ import print_function

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

假设您有以下文本文件:

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

如果打开它,逐行读取并打印,则每行有两个\n;一个在文件的每行中,一个在默认情况下放在print

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

Line 2

Line 3

Line 4

有很多方法可以做到这一点。你知道吗

可以使用.rstrip()删除\n

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

您可以使用,来抑制自动\n

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

在Python3.x中使用print function,它也可以在Python2中导入。你知道吗

干杯!你知道吗

相关问题 更多 >

    热门问题