如何在python中查找和复制子目录的内容?

时间:2019-03-29 22:19:26

标签: python python-3.x os.walk

我有一个根文件夹,其结构为

root
    A 
    |-30
       |-a.txt
       |-b.txt 
    |-90
       |-a.txt
       |-b.txt  
    B
    |-60
       |-a.txt
       |-b.txt  
    C
    |-200
       |-a.txt
       |-b.txt  
    |-300 
       |-a.txt
       |-b.txt 

我想找到所有子文件夹(A,B,C,D),使子文件夹的子文件夹(如30,90,...)小于 60 。然后将子文件夹中所有名称为a.txt的文件复制到另一个目录。和输出喜欢

root_filter
    A 
    |-30
       |-a.txt
    B
    |-60
       |-a.txt

我正在使用python,但无法获得结果

dataroot = './root'
for dir, dirs, files in os.walk(dataroot):
    print (dir,os.path.isdir(dir))

1 个答案:

答案 0 :(得分:1)

基本上,只需要在复制文件之前对您的位置进行一些检查即可。这可以通过在if循环内的简单for语句中使用多个子句来实现:

import shutil
import os

dataroot = './root'
target_dir = './some_other_dir'
for dir, dirs, files in os.walk(dataroot):
    # First, we want to check if we're at the right level of directory
    #   we can do this by counting the number of '/' in the name of the directory
    #   (the distance from where we started). For ./root/A/30 there should be 
    #   3 instances of the character '/'
    # Then, we want to ensure that the folder is numbered 60 or less.
    #   to do this, we isolate the name of *this* folder, cast it to an int,
    #   and then check its value
    # Finally, we check if 'a.txt' is in the directory
    if dir.count('/') == 3 and int(dir[dir.rindex('/')+1:]) <= 60 and 'a.txt' in files:
        shutil.copy(os.path.join(dir, 'a.txt'), target_dir)

将文件复制到target_dir时,您需要做一些工作来命名文件,因此它们不会相互覆盖。这取决于您的用例。