import os import shutil from openpyxl import load_workbook def create_txt_in_subfolder(subfolder_path, content): txt_filename = os.path.basename(subfolder_path) + ".txt" txt_path = os.path.join(subfolder_path, txt_filename) with open(txt_path, 'w', encoding='utf-8') as txt_file: txt_file.write(content) def main(): excel_path = input("请输入参照的excel表格地址: ") root_dir = input("请输入文件夹总地址: ") target_dir = input("请输入文件夹移动路径: ") input_col = int(input("请输入excel表格的输入列(输入数字): ")) output_col = int(input("请输入excel表格的输出列(输入数字): ")) try: wb = load_workbook(excel_path) sheet = wb.active except Exception as e: print(f"加载Excel文件失败: {e}") return folder_info = {} for row in sheet.iter_rows(min_row=2, values_only=True): input_value = str(row[input_col-1]).strip() output_value = str(row[output_col-1]).strip() folder_info[input_value] = output_value unmatched_folders = [] for subdir in os.listdir(root_dir): subdir_path = os.path.join(root_dir, subdir) if os.path.isdir(subdir_path): if subdir in folder_info: content = folder_info[subdir] create_txt_in_subfolder(subdir_path, content) print(f"在文件夹{subdir}中创建了txt文件。") else: unmatched_folders.append(subdir_path) if unmatched_folders: os.makedirs(target_dir, exist_ok=True) for folder in unmatched_folders: try: shutil.move(folder, target_dir) print(f"未匹配的文件夹{os.path.basename(folder)}已移动到{target_dir}。") except Exception as e: print(f"移动文件夹{os.path.basename(folder)}时发生错误: {e}") print("处理完成。") if __name__ == "__main__": main()
标签:重命名,MJ,subdir,input,path,folder,txt,os From: https://www.cnblogs.com/zly324/p/18215675