简体   繁体   English

如何从目录中的文件夹名称中提取后缀字符串? (蟒蛇)

[英]How to Extract A String of the Suffix from Folder Names in a Directory? (Python)

I have a directory full of non-empty directories, all with the same prefix, but different numbers at the end. 我有一个充满非空目录的目录,所有目录都具有相同的前缀,但末尾的编号不同。 Eg 例如

ABCDE_0003
ABCDE_0005
ABCDE_0007
ABCDE_0009
ABCDE_0011

I would like to extract the number at the end of these directory names, excluding the 0's, into a list from which I can call the indices (numbers) for other automated purposes: 我想将这些目录名称末尾的数字(不包括0的数字)提取到一个列表中,我可以从该列表中调用索引(数字)用于其他自动化目的:

[3,5,7,9,11]

I have tried searching for solutions to this and have found that others have done this for file names, but not directories such as in this thread: 我尝试搜索解决方案,发现其他人已经为文件名执行了此操作,但没有执行此线程之类的目录:

Extract substring from filename in Python? 从Python中的文件名中提取子字符串?

Perhaps there are similar methods to those mentioned in the above thread. 也许有与上述线程中提到的方法类似的方法。 I contemplated that a plausible solution could be to have a script convert the directory names into strings, and then it may be easier to extract the number prefixes that way, but I have not found how to do that either. 我考虑了一个可行的解决方案,那就是让脚本将目录名称转换为字符串,然后以这种方式提取数字前缀可能会更容易,但是我也没有找到如何做到这一点。 Any ideas? 有任何想法吗?

import os

all_list = os.listdir('.')
numbers = list(
    map(lambda x: int(x[6:]), filter(lambda x: os.path.isdir(x) and x.startswith("ABCDE_"), all_list))
)
# python3
print(numbers)
# python2
print numbers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM