如何查找和复制python中子目录的内容?
How to find and copy the content of sub directories in python?
我有一个根文件夹,其结构如下
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))
基本上,您只需要 运行 在复制文件之前检查一下您的位置。这可以通过 for
循环内的简单 if
语句中的多个子句来完成:
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
时,您需要为文件命名,这样它们就不会相互覆盖。这取决于您的用例。
我有一个根文件夹,其结构如下
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))
基本上,您只需要 运行 在复制文件之前检查一下您的位置。这可以通过 for
循环内的简单 if
语句中的多个子句来完成:
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
时,您需要为文件命名,这样它们就不会相互覆盖。这取决于您的用例。