1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Python新建 写入和修改txt(文本文档)

Python新建 写入和修改txt(文本文档)

时间:2023-01-24 00:20:14

相关推荐

Python新建 写入和修改txt(文本文档)

新建、写入:

# 创建一个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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。