首页 > 解决方案 > Python:.strip() 和 .write() 似乎会产生空格

问题描述

我写了一些代码让我在不学习它们的命令的情况下输入特殊字符,所以我写了这个:

file = open('test.txt', 'r+')
text = file.read()

text = text.replace('//a', 'Ä')
text = text.replace('//o', 'Ö')
text = text.replace('//u', 'Ü')

text = text.replace('/a', 'ä')
text = text.replace('/o', 'ö')
text = text.replace('/u', 'ü')

text = text.replace('/s', 'ß')

file.truncate(0) # Clears the file
file.write(text.strip()) # edit was .strip(''), made no diffence 
print(text)

一个示例输入是“n/achtes”,它将变成“nächtes”这种工作,但是当我运行文件时,我在文本文件中得到大量空白,例如“n/achtes”变成:

 '        nächtes'

如果我第二次运行程序,sublimetext 3 上的输出以 nächtes 结尾,但有 8 个不同颜色的 <0x00> 不可复制副本。文本文件中的空格数量也会增加。

标签: pythonpython-3.x

解决方案


truncate(0)将文件大小调整为零大小,但当前位置不变。

写入数据时,它被写入当前位置,因此文件的其余部分将空字节写入“填充”。

最好使用truncate()不带参数来截断当前位置的文件:

f.seek(0)    # go to the beginning of the file
f.truncate() # truncate in current position

推荐阅读