Python批量替换文件中指定字符串

不管是txt文件还是xml文件还是其他的,都可以用这种方法来批量替换文件中字符串:

# -*- coding:utf-8 -*-
__author__ = 'ShawDa'


import glob

xmls = glob.glob('xml_files/*.xml')
for one_xml in xmls:
    print(one_xml)
    f = open(one_xml, 'r+', encoding='utf-8')
    all_the_lines = f.readlines()
    f.seek(0)
    f.truncate()
    for line in all_the_lines:
        line = line.replace('dog', 'pig')
        line = line.replace('cat', 'bike')
        f.write(line)
    f.close()

你可能感兴趣的:(Python批量替换文件中指定字符串)