问题描述
我正在编写一个Python脚本,该脚本列出了目录中的目录。任务似乎很简单。
但是,就我而言,我想做一些更复杂的事情。说我有以下结构
thelist=list(glob.glob('./*/conditionfolder/conditionfile'))
print(thelist)
到目前为止,该脚本仅列出了目录:
- 文件夹1
- folder2
- folder3
但是我希望脚本仅列出符合条件的目录
例如,如果我要列出具有名为“ conditionfolder”的子目录的目录,则会得到
- 文件夹1
- folder2
另一方面,如果我要列出具有名为“ conditionfolder”的子目录的目录,并且在其中有一个名为“ conditionfile”的文件,则
- 文件夹1
如何在python中做到这一点?
编辑:
在@Susmit Agrawal回答之后,我这样做了:
['.\\folder1\\conditionfolder\\conditionfile']
所以现在我有了以下形式的列表:
['folder1']
太好了。但是理想情况下,我想拥有这个
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.66 Driver Version: 450.66 CUDA Version: 11.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 GeForce GTX 108... Off | 00000000:26:00.0 Off | N/A |
| 0% 49C P8 9W / 250W | 18MiB / 11177MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
| 1 GeForce GTX 1050 Off | 00000000:27:00.0 Off | N/A |
| 57% 44C P8 N/A / 75W | 7MiB / 2000MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
仅表示文件夹列表。 我猜我可以对原始列表进行操作以通过拆分生成另一个列表
解决方法
如果条件可以在命令行上描述为正则表达式,则最简单的方法是使用glob
:
import glob
for path in glob.glob('./*/conditionfolder'):
# extract required directory name from *path*
'./*/conditionfolder'
可以用命令行上可用的任何正则表达式替换。
您可以利用os.walk并遍历目录结构并根据条件进行打印。
import os
path_to_consider = r'c:\dev\testFolder'
for root,directory,file in os.walk(path_to_consider,topdown=True):
for d in directory:
if d == 'conditionfolder':
print(f"The folder containing conditionFolder is {root}")
for f in file:
if f == 'conditionfile.txt':
print(f"The folder containing conditionFile is {root}")