如何避免在python 3x的readline()函数中出现新行?

How to avoid new line in readline() function in python 3x?

本问题已经有最佳答案,请猛点这里访问。

我是Python编程的新手。我已经遵循了"学习Python硬方法"这本书,但它是基于Python2X的。

1
2
def print_one_line(line_number,f):
    print(line_number,f.readline())

在这个函数中,每次它打印一行和一行新行时。

1
2
3
4
5
1 gdfgty

2 yrty

3 l

我读了这部纪录片,如果我在阅读行后加上(逗号)然后它将不会打印新的。这是纪录片:

Why are there empty lines between the lines in the file? The
readline() function returns the
that's in the file at the end of
that line. This means that print's
is being added to the one
already returned by readline() fuction. To change this behavior simply add a ,
(comma) at the end of print so that it doesn't print its own .

当我使用python 2x运行文件时,它是正常的,但是当我使用python 3x运行文件时,会打印换行符。如何避免在python 3x中出现换行符?


由于您的内容已经包含了所需的换行符,请告诉print()函数不要使用可选的end参数添加任何换行符:

1
2
def print_one_line(line_number,f):
    print(line_number,f.readline(), end='')

除其他方法外,您还可以使用:

1
2
import sys
sys.stdout.write(f.readline())

适用于迄今为止的所有Python版本。


您可以从输入中去掉换行符,而不是在输出中跳过换行符:

1
2
print(line_number, f.readline().rstrip('
'
))