当前位置: 首页 > news >正文

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("提示:请检查路径权限和磁盘空间")

相关文章:

  • 【PCIE配置空间】
  • 软件中的保护锁在工程项目中的应用
  • C算术运算符 printf输出格式 字符指针打印输出 使用scanf函数进行输入
  • MCGS昆仑通太屏笔记
  • 【mongodb】数据库操作
  • OSI七层网络模型详解
  • 【MySQL】MySQL建立索引不知道注意什么?
  • OpenStack Yoga版安装笔记(23)Swift安装
  • 六边形棋盘格(Hexagonal Grids)的坐标
  • OPC_KEPServerEX 6 安装与授权
  • 【KWDB 创作者计划】_上位机知识篇---Docker容器
  • 提升电脑性能!Windows超级管理器,免费使用,功能全面!
  • 故障诊断 | CNN-BiGRU-Attention故障诊断
  • 真实波幅策略思路
  • uniapp-x 二维码生成
  • 【愚公系列】《Python网络爬虫从入门到精通》054-Scrapy 文件下载
  • 多道程序和多任务操作系统区别
  • spring三级缓存如何解决循环依赖问题
  • Java Web 之 Tomcat 100问
  • C语言 数组(下)
  • 菲律宾群岛地区发生5.6级地震,震源深度20千米
  • 科普|军团菌肺炎:春末夏初的隐形健康威胁
  • 石黑一雄《莫失莫忘》与“克隆人”:殖民地的记忆与行动
  • 一代油画家的“色彩之诗”:周碧初捐赠艺术展上海举行
  • 中华民族共同体体验馆第二期在北京开展,上海体验区展现人民城市与民族团结交融之美
  • 推动行业健康发展,上海发布医药企业防范商业贿赂案例手册