用Python写文件时换行字符(n)重复?



我正在编写一个简单的程序,它向服务器(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',则没有任何更改。我错过了什么?

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

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

最新更新