import os
import shutil
def move_dir(src_dir=None, dst_dir='new_dir', find_key='case_data_stub.json'):
'''
从当前文件夹中,遍历每个文件夹,
找到包括find_key的文件夹,剪切到dst_dir路径中
'''
find_num = 0
cur_path = os.getcwd()
print("当前路径:", cur_path)
dst_dir = os.path.join(cur_path, dst_dir)
print("目的路径:", dst_dir)
for dirpath, dirnames, filenames in os.walk(cur_path):
for dirname in dirnames:
full_path = os.path.join(dirpath, dirname)
if os.path.isfile(full_path):
continue
# 到此,得到了完整的路径,full_path
for file in os.listdir(full_path):
if os.path.isfile(os.path.join(full_path, file)):
if file == find_key and dst_dir not in full_path:
find_num += 1 # 找到的个数+1
print("找到了find_key, full_path: ", full_path)
if os.path.exists(dst_dir):
# 如果文件夹已存在,先删除,再创建
print("文件夹已存在,先删除,再创建: ", dst_dir)
shutil.rmtree(dst_dir)
os.mkdir(dst_dir)
else:
print("文件夹不存在, 创建文件夹: ", dst_dir)
os.mkdir(dst_dir)
shutil.move(full_path, dst_dir)
return find_num
if __name__ == '__main__':
find_num = move_dir(dst_dir='new_dir')
print("找到了多少个:", find_num)