A, file batch rename
XLS import XLRD import XLWT import OS import re import sys class MyFilter(object): def __init__(self, mylogfile=sys.stdout): self.f = mylogfile def write(self, data): if "WARNING *** OLE2 inconsistency" not in data: self.f.write(data) # start up log = open("the_log_file.txt", "W ") log_filter = MyFilter(log) # book = XLRD. Open_workbook ("foo.xls", logfile=log_filter) # If not, find def find_file_code(title, sheet_name): Reg = "[0-9a-za-z-_]+" match_value = re.search(reg, title) # result = match_value.group() if re.search(r"[a-zA-Z]+", result): return result match_value = re.search(reg, sheet_name) if match_value: Group () return None Folder = 'C:\\Users\\ Desktop\\ weekend \3, 202106\\shiyan\ 'fixed_name =' os.listdir(folder) for department_name in fixed_name: work_path = folder + department_name + "\\" filenamelist = os.listdir(work_path) for i in filenamelist: If not I.E ndswith(".xls"): Workbook = xlrd.open_workbook(work_path + I, formatting_info=True, Logfile =log_filter) # print(workbook.sheet_names()) # print(workbook.sheet_names() workbook.sheet_by_index(0) print('sheet', i, sheet1.cell_value(0, 0)) # print(sheet1) file_code = find_file_code(sheet1.cell_value(0, 0), workbook.sheet_names()[0]) handled = False if file_code and not file_code.startswith("Sheet"): new_file_name = work_path + file_code + "-" + department_name + ".xls" new_file_name = new_file_name.replace("--", "-") if not os.path.exists(new_file_name): os.rename(work_path + i, new_file_name) handled = True else: Print (department_name + work_path + I + "file not processed ") # print(new_name)Copy the code
2. Batch copy of files
Import shutil, OS Folder = 'C:\\Users\\ Desktop\\ weekend \3, 202106\\shiyan\ 'target = R 'c :\Users\ Desktop\ weekend \3, 202106\test' fixed_name = OS. Listdir (Folder) for department_name in fixed_name: source = folder+ department_name filenamelist = os.listdir(source) # print(os.listdir(source)) for file in filenamelist: print(file) if file.endswith('.xls'): try: shutil.copy(source+'\\'+file,target+"\\"+file) except IOError as e: print("unable to copy file .%s" % e)Copy the code