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

在此记录下,用python将layout下的xml文件中的@dimen/dpxxx改为(xxx/3)dp。

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()

注意格式,TAB和空格不能混用,会报TabError: inconsistent use of tabs and spaces in indentation

你可能感兴趣的:(脚本工具)