新建、写入:
# 创建一个txt文件,文件名为first file,并向文件写入msg
def File_New(name, msg):
desktop_path = “路径” #文件路径
full_path = desktop_path + name + ‘.txt’ # 也可以是.doc
file = open(full_path,’w’)
file.write(msg)
file.close()
text_create(‘first file’, ‘Hi!Python!’)
# 调用函数创建一个名为first file的.txt文件,并向其写入Hi!Pythpn!
修改:
def UpdateFile(file,old,new):
file_data = “路径”
with open(file, “r”, encoding=”utf-8″) as f:
for line in f:
if old_str in line:
line = line.replace(old,new)
file_data += line
with open(file,”w”,encoding=”utf-8″) as f:
f.write(file_data)
UpdateFile(r”路径\first file.txt”, “zdz”, “administrator”)#将路径中的first file.txt文件把所有的zdz改为administrator