简体   繁体   中英

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:

[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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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