【问题标题】:Newline character (\n) duplicates when writing a file with Python?使用 Python 编写文件时换行符 (\n) 重复?
【发布时间】:2022-03-22 01:02:01
【问题描述】:

我正在编写一个简单的程序,它将字节发送到服务器(UDP 连接),服务器回显字节,然后我将回显写入输出文件。主要功能如下:

def communication_into_server(s, size, filename):
    f = open(filename, 'rb')
    while True:
        line = f.read(size)
        if line == b'':
            break
        s.send(line)
    f.close()
    s.send(b"EOF")

def communication_from_server(s, size):
    g = open("output.txt", 'w', encoding="utf-8")
    while True:
        line = s.recv(size)
        print(line.decode("utf-8"))
        if line == b'EOF':
            break
        g.write(line.decode("utf-8"))
    g.close()

一些示例文本是这样的:

This is some sample text
with a single newline character.

它的输出如下所示:

This is some sample text

with a single newline character.

显然,\n 字符在某处被重复。请注意第二个函数上的 print()。它打印这个:

This is some sample text
with a single newline character.

没有额外的换行符,因此问题似乎不在连接中。如果我在打开输出文件时将“w”更改为“a”,则没有任何变化。我错过了什么?

【问题讨论】:

  • 如果您对输出文件进行字节转储,它实际上是否在第一个文本之后包含\n\n?还是包含\r\n
  • \r\n 示例文件,\r\r\n 输出文件
  • 一些系统使用/期望 \r\n 作为换行符,而其他系统将 both \r\n 视为换行符(因此是双换行符)。不管你信不信,这仍然 很多比以前更好。

标签: python file newline write


【解决方案1】:

我遇到了同样的问题,使用 python 保存 markdown 文件,并且每次保存时都会重复空格。 我只是在使用encode 方法将字符串保存到文件之前对字符串进行了编码:

body = body.encode()
# now it can be saved into a file...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多