python遍历文件夹下所有文件并批量修改内容

  • A+
所属分类:Python

python遍历文件夹下所有文件并批量修改内容

import os, shutil,re

if __name__=='__main__':
    work_dir = 'C:\\Users\\Desktop\\workspace\\app\\src\\main\\res\\layout'
    new_dir = 'C:\\Users\\Desktop\\layout_test\\'
    for parent, dirnames, filenames in os.walk(work_dir,  followlinks=True):
        for filename in filenames:
            file_path = os.path.join(parent, filename)
            file = open(file_path,"r+",encoding='UTF-8')
            newFile = open(new_dir+filename,"w",encoding='UTF-8')
            for line in file.readlines():
                if("@dimen/dp" in line):
                    num = re.sub("\D", "", line)
                    newNum = int(num)/3
                    newNum = ("%.1f" % newNum)
                    ori = line.split("\"")
                    line = line.replace(ori[1],str(newNum)+"dp")
                newFile.writelines(line)
            print (filename)
            newFile.close()
            file.close()

 

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin