录入规则文件名到CSV文件
1 import os 2 import sys 3 import csv 4 5 6 # 导出到csv文件 7 8 def export_to_csv(datas): 9 10 with open('export.csv', 'w', newline='') as datacsv: 11 csvwriter = csv.writer(datacsv) 12 csvwriter.writerow(['姓名', '身份证号码']) 13 csvwriter.writerows(datas) 14 # for data in datas: 15 # csvwriter.writerow(data, '\t') 16 17 18 # 遍历一个目录 19 20 def trav_dir(dir, datas): 21 22 file_list = os.listdir(dir) 23 for file in file_list: 24 # 获取文件完整路径 25 file_path = os.path.join(dir, file) 26 if os.path.isdir(file_path): 27 trav_dir(file_path) 28 else: 29 # # 文件名替换 30 # if str_del in file: 31 # new_file = file.replace(str_del, '') 32 # # 对文件改名 33 # new_file_path = os.path.join(dir, new_file) 34 # # 对文件重命名 35 # rename_file(file_path, new_file_path) 36 # 获取文件名 37 fls = os.path.splitext(file) 38 if fls[1] in '.jpg, .png, jpeg': 39 file = fls[0] 40 index = file.find('4') 41 name = file[0:index] 42 number = '\t' + file[index:] 43 datas.append((name, number)) 44 # print(file[0:index]) 45 # print(file[index:]) 46 47 48 if __name__ == '__main__': 49 # 获取目录 50 if len(sys.argv) >= 2: 51 wk_dir = sys.argv[1] 52 else: 53 print('需要指定一个要录入的文件夹') 54 # wk_dir = '/Users/linxmouse/Desktop/csv' 55 exit(-1) 56 57 datas = [] 58 # 遍历一个目录 59 trav_dir(wk_dir, datas) 60 export_to_csv(datas)