with open(‘user.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
data=f.read()
data=data.replace(‘派大星‘,‘派大星和海绵宝宝‘)
with open(‘user.txt‘,mode=‘w‘,encoding=‘utf-8‘) as f:
f.write(data)
OS
模块import os
: 导入模块os.remove( )
: 删除os.rename( )
: 改名import os
with open(‘user.txt‘,mode=‘rt‘,encoding=‘utf-8‘) as read_f, open(‘user.txt.swap‘,mode=‘wt‘,encoding=‘utf-8‘) as write_f:
for line in read_f:
if ‘派大星‘ in line:
line=line.replace(‘派大星‘,‘派大星和海绵宝宝‘)
write_f.write(line)
os.remove(‘user.txt‘) #删除源文件
os.rename(‘user.txt.swap‘,‘user.txt‘) #把临时文件名改成源文件名
可以拷贝任意类型的文件
??"os.path.isfile()" 先判断文件是否存在
import os
while 1:
user_file = input("请输入文件路径>>").strip()
if not os.path.isfile(user_file):
print("文件不存在,请重新输入")
continue
else:
copy_path = input("请输入目标路径>>").strip()
with open(r"%s"%(user_file),"rb")as read_file, open(r"%s"%(copy_path),"ab")as w_f:
for line in read_file:
w_f.write(line)
if len(user_file) == len(copy_path):
print("copy成功")
break
原文:https://www.cnblogs.com/songhaixing/p/14052842.html