【发布时间】:2021-03-21 17:39:07
【问题描述】:
具有如下树结构:
custom_test/
├── 110/
│ ├── 1548785454_CO_[1].txt
├── 120/
│ ├── 1628785454_C4_[1].txt
└── 13031/
│ ├── 1544725454_C2_[1].txt
└── test_results/
│ ├── resulset1.txt
│ ├── hey.txt
script.py <------- this is the script which runs the Python code
我想获取除test_results 之外的所有文件夹的文件和子文件夹(我想忽略此文件夹)。使用上面的缩小示例,我想要的输出是:
['110\\1548785454_CO_[1].txt', '120\\1628785454_C4_[1].txt', '13031\\1544725454_C2_[1].txt']
这是我的尝试,它产生了输出,但它也包括 test_results 文件夹中的那些:
deploy_test_path = "custom_test"
print([os.path.join(os.path.basename(os.path.relpath(os.path.join(filename, os.pardir))), os.path.basename(filename)) for filename in glob.iglob(deploy_test_path + '**/**', recursive=True) if os.path.isfile(filename)])
没有列表理解(为了更容易理解):
deploy_test_path = "custom_test"
for filename in glob.iglob(deploy_test_path + '**/**', recursive=True):
if os.path.isfile(filename):
a = os.path.join(os.path.basename(os.path.relpath(os.path.join(filename, os.pardir))), os.path.basename(filename))
print(a)
如何归档我的目标?我知道我可以从数组中删除 test_results 的元素,但是还有更优雅和 Pythonic 的等待这样做吗?
提前致谢
【问题讨论】:
-
使用
glob.iglob('custom_test/**[!test_results]/**', recursive=True):这将排除test_result文件夹(仅用于第一级)。另请参阅 this 帖子,其中显示了排除规则以及如何使用集合来排除两种不同的模式。
标签: python python-3.x file directory list-comprehension