Python a = open("文件", "r"); a.readline() 输出没有 \n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39921087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:54:22  来源:igfitidea点击:

a = open("file", "r"); a.readline() output without \n

python

提问by Simon l.

I am about to write a python script, that is able to read a txt file, but with readline() there is always the \n output. How can i remove this from the variable ?

我即将编写一个能够读取 txt 文件的 python 脚本,但是使用 readline() 总是有 \n 输出。我怎样才能从变量中删除它?

a = open("file", "r")
b = a.readline()
a.close()

回答by wim

That would be:

那将是:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

如果你想从每一行中去除空间,你可以考虑:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

这会给你一个行列表,没有行结束字符。

回答by Laurent LAPORTE

A solution, can be:

一个解决方案,可以是:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

你得到没有“\r\n”或“\n”的行列表​​。

Or, use the classic way:

或者,使用经典方式:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

您逐行阅读文件并删除空格和换行符。

If you only want to drop the newlines:

如果您只想删除换行符:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

等等。

Note:The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

注意:Python 3 的行为略有不同。要模仿这种行为,请使用io.open.

See the documentation of io.open.

请参阅io.open的文档。

So, you can use:

因此,您可以使用:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newlineparameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline参数为None: 输入中的行可以以 '\n'、'\r' 或 '\r\n' 结尾,并且这些被转换为 '\n'。

newlinecontrols how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

换行符控制通用换行符的工作方式(它仅适用于文本模式)。它可以是 None、''、'\n'、'\r' 和 '\r\n'。它的工作原理如下:

在输入时,如果换行符为 None,则启用通用换行符模式。输入中的行可以以 '\n'、'\r' 或 '\r\n' 结尾,这些在返回给调用者之前会被转换为 '\n'。如果是 '',则启用通用换行符模式,但行尾会返回给调用者未翻译。如果它具有任何其他合法值,则输入行仅由给定的字符串终止,并且行尾未翻译地返回给调用者。