Python读取文件后调用replace方法未生效的问题排查
问题解决:Python字符串replace未生效的原因及修复
Python中的字符串是不可变对象,str.replace()方法不会直接修改原字符串,而是返回一个完成替换操作的新字符串。你的代码里仅调用了content.replace("Here",""),但没有将返回的新字符串重新赋值给content变量,所以原字符串完全没变化,导致输出看起来替换未生效。
修复后的脚本如下:
with open(r'test.txt',"r") as text_file: content = text_file.read() print("the content:") print(content) # 将replace返回的新字符串赋值给content content = content.replace("Here","") print("The replaced content:") print(content)
如果需要把修改后的内容写回原文件,可以添加写入步骤:
with open(r'test.txt',"r") as text_file: content = text_file.read() content = content.replace("Here","") # 写入修改后的内容 with open(r'test.txt',"w") as text_file: text_file.write(content)
内容的提问来源于stack exchange,提问作者Nathanael Skrepek
相关产品推荐
相关产品推荐

