如何在python中查找和复制子目录的内容?
我有一个根文件夹,其结构如下如何在python中查找和复制子目录的内容?,python,python-3.x,os.walk,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 我希望找
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)
导入shutil
导入操作系统
dataroot='./根'
target_dir='./某些_其他_dir'
对于os.walk(dataroot)中的dir、dirs和文件:
#首先,我们要检查我们是否处于正确的目录级别
#我们可以通过计算目录名中“/”的数量来实现这一点
#(我们从哪里开始的距离)。对于./root/A/30,应该有
#字符“/”的3个实例
#然后,我们要确保文件夹编号为60或更少。
#为此,我们隔离*this*文件夹的名称,将其强制转换为int,
#然后检查它的值
#最后,我们检查目录中是否有“a.txt”
如果dir.count('/')==3和int(dir[dir.rindex('/')+1:]),为什么要检查dir?它总是一个方向。。。您不检查任何文件名,您不将任何内容转换为数字,…,您根本不复制,您不执行完成任务所需的操作。你的具体问题是什么?因为我们需要为您编写所有代码。。。我们通常不会这样做。请查看Jon Skeet的帮助页面和博客文章,以及我们可以回答的特定问题的代码。问题是我找不到像a和30这样的子文件夹。如何找到它?阅读os.walk的文档-dirs
是dataroot的子目录列表-它递归地进入其中的所有dirdir
保存您当前正在观看的目录-这就是它通常被称为root的原因。目录和文件是列表-打印它们。好主意。谢谢我们可以自动计算/
的数量吗。例如,如果根目录为“/home/hee/data/root”,则必须更改编号。您可以将3
替换为(dataroot.count(“/”)+2)
,因为您需要从根目录向下两级。但通常情况下,os.walk()
适用于相对目录-如果您输入'./root'
,那么它将吐出以/root/…
开头的目录。另一个旁注是,此代码可能无法在windows上工作,因为windows使用反斜杠。在这种情况下,您可以将'/'
更改为os.sep
,它存储您当前运行的操作系统使用的“分隔符”。我得到了错误ValueError:int()的无效文本,以10为基数:
我认为行int(dir[dir.index('/')+1:])
。完整错误为ValueError:int()的无效文本,以10为基数:root/A/30