为何每次执行Python脚本后文本文件大小翻倍?
问题原因与解决办法
核心问题出在文件指针的位置上:
- 用
r+模式打开文件后,执行text.read()会把文件指针移到文件末尾。 - 虽然调用
text.truncate(0)清空了文件,但指针并没有回到文件开头,仍然停在原来的末尾位置。 - 此时执行
text.write(text_string),会从指针所在位置开始写入内容,前面的空白区域会被填充空字节,导致文件大小变成「原文件长度 + 新内容长度」,看起来像是翻倍了。
另外你的脚本里还有几个语法错误,不修正会直接报错:
list_to_delete里的""."多打了一个引号,应该改成"."special_characters_to_delete里的" :" "," :" "格式错误,要写成" ":" ", " ":" "list_to_delete里的空字符串""完全没必要,建议删掉,否则会做无意义的替换
修正后的两种写法
写法1:重置文件指针
在truncate(0)之后加上seek(0),把指针移回文件开头再写入:
temp_letter_1 = temp_letter_2 = "" with open("my_text_file.txt", "r+") as text: text_string = text.read() list_to_delete = ["\n","\"","'","«","»","(",".","!","?","^","&","*","_","`","%","#",",","–"] special_characters_to_delete = {"é":"e","è":"e","ê":"e","ë":"e","à":"a","ô":"o","î":"i","û":"u","œ":"oe","/":" ",":":" ",";":" ","-":" ","’":" "," ":" ", " ":" "} for i in list_to_delete: text_string = text_string.replace(i,"") for i in special_characters_to_delete: text_string = text_string.replace(i,special_characters_to_delete[i]) text_string = text_string.lower() text.truncate(0) text.seek(0) # 新增:将文件指针移到开头 text.write(text_string) print(text_string)
写法2:分开读写(更稳妥)
先以只读模式读取内容,再用只写模式打开文件(w模式会自动清空原有内容),彻底避免指针问题:
temp_letter_1 = temp_letter_2 = "" # 只读模式读取内容 with open("my_text_file.txt", "r") as text: text_string = text.read() list_to_delete = ["\n","\"","'","«","»","(",".","!","?","^","&","*","_","`","%","#",",","–"] special_characters_to_delete = {"é":"e","è":"e","ê":"e","ë":"e","à":"a","ô":"o","î":"i","û":"u","œ":"oe","/":" ",":":" ",";":" ","-":" ","’":" "," ":" ", " ":" "} for i in list_to_delete: text_string = text_string.replace(i,"") for i in special_characters_to_delete: text_string = text_string.replace(i,special_characters_to_delete[i]) text_string = text_string.lower() # 只写模式写入,自动清空原有内容 with open("my_text_file.txt", "w") as text: text.write(text_string) print(text_string)
内容的提问来源于stack exchange,提问作者Ramen Osaka
相关产品推荐
相关产品推荐

