⽤python修改⽂件内容修改txt内容的3种⽅法⽤python修改⽂件内容修改txt内容的3种⽅法
⽅法⼀、修改原⽂件⽅式
def updateFile(file,old_str,new_str):
"""
替换⽂件中的字符串
python干嘛用的:param file:⽂件名
:param old_str:就字符串
:param new_str:新字符串
:return:
"""
file_data = ""
with open(file, "r", encoding="utf-8") as f:
for line in f:
if old_str in line:
line = place(old_str,new_str)
file_data += line
with open(file,"w",encoding="utf-8") as f:
f.write(file_data)
updateFile(r"D:\", "zdz", "daziran")#将"D:\zdz\"路径的⽂件把所有的zdz改为daziran
⽅法⼆、python字符串替换的⽅法,修改⽂件内容,把原⽂件内容和要修改的内容写到新⽂件中进⾏存储的⽅式import os
def updateFile(file,old_str,new_str):
"""
将替换的字符串写到⼀个新的⽂件中,然后将原⽂件删除,新⽂件改为原来⽂件的名字
:param file: ⽂件路径
:param old_str: 需要替换的字符串
:param new_str: 替换的字符串
:return: None
"""
with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
for line in f1:
if old_str in line:
line = place(old_str, new_str)
f2.write(line)
updateFile(r"D:\", "zdz", "daziran")#将"D:\zdz\"路径的⽂件把所有的zdz改为daziran
⽅法三、python 使⽤正则表达式替换⽂件内容 re.sub ⽅法替换
import re,os
def updateFile(file,old_str,new_str):
with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
for line in f1:
f2.write(re.sub(old_str,new_str,line))
updateFile(r"D:\", "zdz", "daziran")#将"D:\zdz\"路径的⽂件把所有的zdz改为daziran
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论