Python file.write 创建额外的回车

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4025760/
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-18 13:54:26  来源:igfitidea点击:

Python file.write creating extra carriage return

pythonwindowseol

提问by Chris

I'm writing a series of SQL statements to a file using python. The template string looks like:

我正在使用 python 将一系列 SQL 语句写入文件。模板字符串如下所示:

store_insert = '\tinsert stores (storenum, ...) values (\'%s\', ...)'

I'm writing to the file like so:

我正在写入文件,如下所示:

for line in source:
    line = line.rstrip()
    fields = line.split('\t')
    script.write(store_insert % tuple(fields))
    script.write(os.linesep)

However, in the resulting output, I see \r\r\n at the end of each line, rather than \r\n as I would expect. Why?

但是,在结果输出中,我在每一行的末尾看到 \r\r\n,而不是我期望的 \r\n。为什么?

采纳答案by adw

\nis converted to os.linesepfor files opened in text-mode. So when you write os.linesepto a text-mode file on Windows, you write \r\n, and the \ngets converted resulting in \r\r\n.

\n转换为os.linesep用于以文本模式打开的文件。因此,当您os.linesep在 Windows 上写入文本模式文件时,您会写入\r\n,然后\n转换为\r\r\n.

See also the docs:

另请参阅文档

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

在写入以文本模式(默认)打开的文件时,不要使用 os.linesep 作为行终止符;在所有平台上使用单个 '\n' 代替。

回答by mouad

see the open() doc:

请参阅open() 文档:

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

除了标准的 fopen() 值模式之外,模式可能是“U”或“rU”。Python 通常使用通用换行支持构建;提供 'U' 将文件作为文本文件打开,但行可以由以下任何一种终止:Unix 行尾约定 '\n'、Macintosh 约定 '\r' 或 Windows 约定 '\ r\n'。所有这些外部表示都被 Python 程序视为“\n”。如果 Python 是在没有通用换行支持的情况下构建的,则带有 'U' 的模式与普通文本模式相同。请注意,如此打开的文件对象也有一个名为换行符的属性,其值为 None(如果尚未看到换行符)、'\n'、'\r'、'\r\n' 或包含所有内容的元组看到的换行符类型。

回答by Katriel

Works for me:

对我有用:

>>> import tempfile
>>> tmp = tempfile.TemporaryFile(mode="w+")
>>> store_insert = '\tinsert stores (storenum, ...) values (\'%s\', ...)'
>>> lines = ["foo\t\t"]
>>> for line in lines:
...     line = line.rstrip()
...     fields = line.split("\t")
...     tmp.write(store_insert % tuple(fields))
...     tmp.write(os.linesep)
...
>>> tmp.seek(0)
>>> tmp.read()
"\tinsert stores (storenum, ...) values ('foo', ...)\r\n"

Are you sure this is the code that's running, that os.linesepis what you think it is, etc?

你确定这是正在运行的代码,这os.linesep就是你认为的,等等?

回答by Mark Ransom

Text files have different line endings on different operating systems, but it's convenient to work with strings that have a consistent line ending character. Python inherits the convention from C of using '\n'as the universal line ending character and relying on the file read and write functions to do a conversion, if necessary. The read and write functions know to do this if the file was opened in the default textmode. If you add the bcharacter to the mode string when opening the file, this translation is skipped.

文本文件在不同的操作系统上有不同的行尾,但使用具有一致行尾字符的字符串很方便。Python 继承了 C 的约定,即'\n'用作通用行结束符,并在必要时依靠文件读写函数进行转换。如果文件是在默认text模式下打开的,则读写函数知道这样做。如果b在打开文件时将字符添加到模式字符串中,则会跳过此转换。

回答by Daniele Bacarella

With Python 3

使用 Python 3

open()introduces the new parameter newlinethat allows to specify a string which any occurrence of \nwill be translated to.

open()引入了新参数newline,该参数允许指定任何出现的\n将被转换为的字符串。

Passing an empty string argument newline=''disables the translation, leaving the new line char as it is. Valid for text mode only.

传递空字符串参数newline=''会禁用翻译,保留新行字符原样。仅对文本模式有效。

From the documentation

从文档

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

在输出时,如果换行符为 None,则写入的任何 '\n' 字符都将转换为系统默认行分隔符 os.linesep。如果换行符是 '',则不进行翻译。如果换行符是任何其他合法值,则写入的任何 '\n' 字符都将转换为给定的字符串。