文件树中所有特定命名的文件夹复制:
相关命令
1)os.listdir(path) 第一级目录的文件夹和文件,不会返回子文件夹的文件。
2)os.walk(top, topdown=True)遍历所有内容物,包括子文件夹的文件。
查找特定子文件夹并移动到新目录
以下将D盘中子文件名含“t2*dar-fluid”的子文件夹移动到ubuntu系统,以原文件树中“t2*dar-fluid”上级目录的名称信息加上D盘一级子文件夹的日期信息为新的文件夹命名:
jupyter nbconvert --execute --to python '/mnt/c/Users/yinwe/MyDoc/LogsForWorksInUbuntu/sF_copy_from_disc.ipynb'
或者
import os
import re
import shutil
os.chdir('/mnt/d/')
print(os.getcwd())
root = '/mnt/d/'
str_nums = [str(i) for i in range(10)]
cnt_eneum = 0
cnt_val = 0
dup_log = []
for date_dir in os.listdir(root):
if date_dir[0] in str_nums: # 如上述终端截图,有硬盘配置等文件需要区别开
cnt_eneum += 1
name_path = root + date_dir +'/'
for name_dir in os.listdir(name_path):
imgcla_path = name_path + name_dir +'/'
name = re.sub(r'[\s+]', '', name_dir)
for imgcla in os.listdir(imgcla_path):
#if bool(re.search(r't2.*dark-fluid', imgcla)):
if 't2' in imgcla and 'dark-fluid' in imgcla: # 目标子文件夹
src = imgcla_path + imgcla
new_name = date_dir + '_' + name + '_' + 't2darkf'
dst = '/mnt/c/Users/yinwe/MyDoc/LogsForWorksInUbuntu/dataFLAIR/' + new_name
while os.path.exists(dst):
dst = dst+'_1'
dup_log.append(dst)
print('NOtice: duplicated target image. ', dst)
shutil.copytree(src, dst)
cnt_val += 1
print('enemerated dirs:', cnt_eneum, 'copied dirs:', cnt_val, '\n', dup_log)
遍历、移动、删除
shutil有copy和move命令,第二参数若为文件夹,则为移动或复制到文件夹下,若为文件名,则为移动或复制后重命名。
os有删除指定文件的功能。shutil的rmtree可以删除整个文件夹。