73 lines
2.6 KiB
Python
73 lines
2.6 KiB
Python
|
|
import os
|
||
|
|
import shutil
|
||
|
|
|
||
|
|
|
||
|
|
def move_xml_files(source_folder, target_folder, recursive=True):
|
||
|
|
"""
|
||
|
|
将 source_folder 中的 .xml 文件移动到 target_folder
|
||
|
|
|
||
|
|
:param source_folder: 源文件夹路径
|
||
|
|
:param target_folder: 目标文件夹路径
|
||
|
|
:param recursive: 是否递归查找子文件夹
|
||
|
|
"""
|
||
|
|
# 检查源文件夹是否存在
|
||
|
|
if not os.path.exists(source_folder):
|
||
|
|
print(f"❌ 源文件夹不存在: {source_folder}")
|
||
|
|
return
|
||
|
|
|
||
|
|
# 如果目标文件夹不存在,创建它
|
||
|
|
os.makedirs(target_folder, exist_ok=True)
|
||
|
|
|
||
|
|
# 统计移动的文件数
|
||
|
|
moved_count = 0
|
||
|
|
|
||
|
|
# 选择遍历方式
|
||
|
|
if recursive:
|
||
|
|
# 递归遍历所有子文件夹
|
||
|
|
for root, dirs, files in os.walk(source_folder):
|
||
|
|
for file in files:
|
||
|
|
if file.lower().endswith('.xml'):
|
||
|
|
src_path = os.path.join(root, file)
|
||
|
|
dst_path = os.path.join(target_folder, file)
|
||
|
|
|
||
|
|
# 防止重名冲突(可选)
|
||
|
|
counter = 1
|
||
|
|
original_dst = dst_path
|
||
|
|
while os.path.exists(dst_path):
|
||
|
|
name, ext = os.path.splitext(file)
|
||
|
|
dst_path = os.path.join(target_folder, f"{name}_{counter}{ext}")
|
||
|
|
counter += 1
|
||
|
|
|
||
|
|
shutil.move(src_path, dst_path)
|
||
|
|
print(f"✅ 移动: {src_path} -> {dst_path}")
|
||
|
|
moved_count += 1
|
||
|
|
else:
|
||
|
|
# 只遍历当前目录
|
||
|
|
for file in os.listdir(source_folder):
|
||
|
|
src_path = os.path.join(source_folder, file)
|
||
|
|
if os.path.isfile(src_path) and file.lower().endswith('.xml'):
|
||
|
|
dst_path = os.path.join(target_folder, file)
|
||
|
|
|
||
|
|
# 防止重名(可选)
|
||
|
|
counter = 1
|
||
|
|
original_dst = dst_path
|
||
|
|
while os.path.exists(dst_path):
|
||
|
|
name, ext = os.path.splitext(file)
|
||
|
|
dst_path = os.path.join(target_folder, f"{name}_{counter}{ext}")
|
||
|
|
counter += 1
|
||
|
|
|
||
|
|
shutil.move(src_path, dst_path)
|
||
|
|
print(f"✅ 移动: {src_path} -> {dst_path}")
|
||
|
|
moved_count += 1
|
||
|
|
|
||
|
|
print(f"\n🎉 完成!共移动 {moved_count} 个 XML 文件。")
|
||
|
|
|
||
|
|
|
||
|
|
# ==========================
|
||
|
|
# 使用示例
|
||
|
|
# ==========================
|
||
|
|
if __name__ == "__main__":
|
||
|
|
source = "/home/hx/桌面/image/image" # 修改为你的源文件夹
|
||
|
|
target = "/home/hx/桌面/image/image/1" # 修改为你的目标文件夹
|
||
|
|
|
||
|
|
move_xml_files(source, target, recursive=True)
|