python文件处理自用
# import os# # 指定要删除的文件夹路径
# folder_path = r"E:\22222\FlawData\2025_04_05\250405074447946" # 替换为你的文件夹路径# # 遍历文件夹中的所有文件
# for filename in os.listdir(folder_path):
# # 检查文件是否以 .txt 结尾
# if filename.endswith(".txt"):
# file_path = os.path.join(folder_path, filename)
# # 确保这是一个文件而不是文件夹
# if os.path.isfile(file_path):
# try:
# os.remove(file_path)
# print(f"已删除: {file_path}")
# except Exception as e:
# print(f"删除文件时出错: {file_path}, 错误: {e}")# 清空空文件夹
# import os# def delete_empty_folders(path):
# """
# 删除指定路径下的所有空文件夹(包括嵌套的空文件夹)。
# """
# if not os.path.exists(path):
# print(f"路径 '{path}' 不存在。")
# return# if not os.path.isdir(path):
# print(f"'{path}' 不是一个文件夹。")
# return# # 遍历目录树
# for root, dirs, files in os.walk(path, topdown=False):
# for dir_name in dirs:
# dir_path = os.path.join(root, dir_name)
# # 检查文件夹是否为空
# if not os.listdir(dir_path):
# os.rmdir(dir_path)
# print(f"已删除空文件夹: {dir_path}")# # 检查根目录本身是否为空
# if not os.listdir(path):
# os.rmdir(path)
# print(f"已删除空文件夹: {path}")# # 示例用法
# path = r"E:\44444" # 替换为你的目标路径
# delete_empty_folders(path)# import os
# import shutil# def move_specific_images(source_dir, target_dir):
# # 删除旧目标文件夹(如果存在)
# if os.path.exists(target_dir):
# shutil.rmtree(target_dir)
# # 创建新目标文件夹
# os.makedirs(target_dir, exist_ok=False)# # 遍历源文件夹及其子目录
# for root, _, files in os.walk(source_dir):
# for file in files:
# # 检查文件名是否符合条件
# if file.startswith('附着物') and file.lower().endswith('.jpg'):
# src_path = os.path.join(root, file)
# dst_path = os.path.join(target_dir, file)# # 执行移动操作(自动覆盖同名文件)
# shutil.move(src_path, dst_path)
# print(f'已移动: {src_path} -> {dst_path}')# if __name__ == '__main__':
# # 设置路径(请替换为实际路径)
# source_folder = r'E:'
# destination_folder = r'E:\heidian' # 完整目标路径# move_specific_images(source_folder, destination_folder)
# print('操作完成:所有文件已剪切到新位置,旧数据已清理')#将指定路径下的所有文件扁平化移动到新路径(取消原有文件夹结构)并删除源文件夹
import os
import shutildef flatten_move_and_delete(source_path, target_path):# 路径规范化处理source_path = os.path.abspath(source_path)target_path = os.path.abspath(target_path)# 安全校验(防止目标路径在源路径内)if target_path.startswith(source_path + os.sep):raise ValueError("错误:目标路径不能在源路径内部")# 创建目标目录os.makedirs(target_path, exist_ok=True)# 第一阶段:收集所有文件路径file_list = []for root, _, files in os.walk(source_path):for filename in files:src_file = os.path.join(root, filename)file_list.append(src_file)# 第二阶段:移动并处理冲突moved_files = []for src_file in file_list:# 构建目标路径dst_file = os.path.join(target_path, os.path.basename(src_file))# 处理文件冲突(强制覆盖)if os.path.exists(dst_file):os.remove(dst_file)# 执行移动操作shutil.move(src_file, dst_file)moved_files.append(dst_file)print(f"已移动: {src_file} -> {dst_file}")# 第三阶段:删除源路径if os.path.exists(source_path):shutil.rmtree(source_path)print(f"已删除源路径: {source_path}")print(f"操作完成!共移动 {len(moved_files)} 个文件")if __name__ == "__main__":# 使用示例(替换实际路径)source = r"E:\33333" # 要处理的源路径target = r"E:\11111" # 目标路径try:flatten_move_and_delete(source, target)except Exception as e:print(f"操作失败: {str(e)}")print("提示:请检查路径权限和磁盘空间")