|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# androidx 整体替换 |
| 3 | + |
| 4 | + |
| 5 | +def traverse_file_replace(src_dir, replace_csv): |
| 6 | + # 遍历文件,并替换文件中的 特殊字符 |
| 7 | + import datetime |
| 8 | + start = datetime.datetime.now() |
| 9 | + |
| 10 | + # 读取csv文件 |
| 11 | + dic = {} |
| 12 | + import csv |
| 13 | + with open(replace_csv) as f: |
| 14 | + row = csv.reader(f, delimiter=',') |
| 15 | + for r in row: |
| 16 | + dic[r[0]] = r[1] |
| 17 | + |
| 18 | + allowFileNum = 0 |
| 19 | + |
| 20 | + import os |
| 21 | + if os.path.exists(src_dir): |
| 22 | + for root, dirs, files in os.walk(src_dir): |
| 23 | + for file in files: |
| 24 | + src_file = os.path.join(root, file) |
| 25 | + |
| 26 | + ALLOWED_EXTENSIONS = {'java', 'kt', 'xml', 'gradle'} |
| 27 | + allowed_file = '.' in src_file and src_file.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS |
| 28 | + if allowed_file: |
| 29 | + allowFileNum = allowFileNum + 1 |
| 30 | + # 替换csv文件中的key,value |
| 31 | + try: |
| 32 | + replace_file(src_file, dic) |
| 33 | + except: |
| 34 | + print('异常文件:------> %s' % src_file) |
| 35 | + continue |
| 36 | + |
| 37 | + end = datetime.datetime.now() |
| 38 | + print('检索文件: %s 个' % allowFileNum) |
| 39 | + print('耗时: %s 秒' % (end - start)) |
| 40 | + |
| 41 | + |
| 42 | +def replace_file(src_file, dic): |
| 43 | + print(src_file) |
| 44 | + # 循环csv文件 |
| 45 | + fp = open(src_file, 'r') |
| 46 | + lines = fp.readlines() # 打开文件,读入每一行 |
| 47 | + fp.close() |
| 48 | + |
| 49 | + fp = open(src_file, 'w+') |
| 50 | + for s in lines: |
| 51 | + # 需要替换文件中的多个字段,并写入新文件fp中 |
| 52 | + for key, value, in dic.items(): |
| 53 | + s = s.replace(key, value) |
| 54 | + |
| 55 | + fp.write(s) |
| 56 | + |
| 57 | + fp.close() # 关闭文件 |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + try: |
| 62 | + print("action start...") |
| 63 | + traverse_file_replace("/Users/xhzh/yxFiles/gitProj/CreditWealthProj", |
| 64 | + "androidx-class-mapping.csv") |
| 65 | + |
| 66 | + except Exception as e: |
| 67 | + print(e) |
| 68 | + input("Please Enter To Finish...") |
0 commit comments