#文件内容替换操作
import os
old_str = '不要回答!'
new_str = '绝对不能回答!'
f = open('test_file','r',encoding='utf-8')
new_f = open('file_new','w',encoding='utf-8')
for i in f:
if old_str in i:
new_line = i.replace(old_str,new_str)
else:
new_line = i
new_f.write(new_line)
f.close()
new_f.close()
os.replace('file_new','test_file')
#在文件里加新加一行内容内容不影响其他内容
import os
file = open('test_file','r',encoding='utf-8')
content = file.readlines()
content.insert(5,'welcome to nice_xm\n')
file_new = open('new_file','w',encoding='utf-8')
content = ''.join(content)
print(content)
file_new.write(content)
file.close()
file_new.close()
os.replace('new_file','test_file')