[英]Newline character (\n) duplicates when writing a file with Python?
I'm writing a simple program that sends bytes to a server (UDP connection), the server echoes the bytes back, and then I write the echo on an output file.我正在编写一个简单的程序,它将字节发送到服务器(UDP 连接),服务器回显字节,然后我将回显写入输出文件。 The main functions are these:主要功能如下:
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()
Some sample text is this:一些示例文本是这样的:
This is some sample text
with a single newline character.
and its output looks like this:它的输出如下所示:
This is some sample text
with a single newline character.
Apparently, \n characters are being duplicated somewhere.显然, \n 字符在某处被复制。 Note the print() on the second function.请注意第二个函数上的 print()。 It prints this:它打印这个:
This is some sample text
with a single newline character.
without the extra newline character, so the problem doesn't appear to be in the connection.没有额外的换行符,所以问题似乎不在连接中。 If I change 'w' to 'a' while opening the output file, nothing changes.如果我在打开输出文件时将“w”更改为“a”,则没有任何变化。 What am I missing?我错过了什么?
I had the same problem, saving markdown files using python, and the spaces were being duplicated on each save.我遇到了同样的问题,使用 python 保存 markdown 文件,并且每次保存时都会复制空格。 I simply encoded the string before saving it in a file using the encode
method:我只是在使用encode
方法将字符串保存到文件之前对字符串进行了编码:
body = body.encode()
# now it can be saved into a file...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.