功能说明
将源目录下子目录中的文件移动到指定目的目录。要求如下:
- 子目录中仅包含指定扩展名的文件才会移动文件。
- 如果目的目录已包含同名文件,将文件重命名为
原文件名 13位时间戳
例如:
当前目录结构如下:
test
│ 2.txt
│
├─1
│ │ 1.txt
│ │
│ └─2
│ 2.txt
│
├─2
│ │ 3.txt
│ │
│ └─3
└─3
2.txt
运行后的目录结构如下:
test
│ 2 1618156462496.txt
│ 2.txt
│
├─1
│ │ 1.txt
│ │
│ └─2
│ 2.txt
│
├─2
│ │ 3.txt
│ │
│ └─3
└─3
仅移动了子目录3
中的2.txt
。由于1
、2
子目录包含子目录,因此其目录中的文件不会被移动。
代码
import os
import shutil
import time
from pathlib import Path
# 生成时间戳
def now_to_timestamp(digits=13):
time_stamp = time.time()
digits = 10 ** (digits - 10)
time_stamp = int(round(time_stamp*digits))
return time_stamp
# 移动文件
def move_files(src_dir, dest_dir, ext_filter):
'''
src_dir:源目录
dest_dir:目的目录
ext_filter:扩展名列表
'''
# 获取源目录中的子目录和子文件
sub_dirs = os.listdir(src_dir)
# 遍历子目录、子文件
for sub_dir in sub_dirs:
# 构造子目录路径
sub_dir_path = os.path.join(src_dir, sub_dir)
# 遍历当前子目录
for root, dirs, files in os.walk(sub_dir_path):
# 只有当前子目录下仅有文件时,继续运行
ext_list = [i for i in files if not i.lower().endswith(ext_filter)]
if root == sub_dir_path and len(dirs) == 0 and len(files) > 0 and len(ext_list) == 0:
for file in files:
# 构造文件路径
file_path = os.path.join(root, file)
new_file_path = os.path.join(dest_dir, file)
# 检测文件扩展名是否符合要求
if Path(file_path).suffix.lower() in ext_filter:
# 检测目的文件路径是否存在,不存在直接移动,存在更名后再移动
if not os.path.exists(new_file_path):
pass
else:
# 重命名文件
new_file_name = Path(
new_file_path).stem + " " + str(now_to_timestamp()) + Path(new_file_path).suffix
new_file_path = os.path.join(
dest_dir, new_file_name)
# 移动文件
shutil.move(file_path, new_file_path)
print(file_path, '->', new_file_path)
if __name__ == '__main__':
src_dir = r'd:\test'
dest_dir = r'd:\test'
exts = ('.txt')
move_files(src_dir, dest_dir, exts)