Skip to main content
 首页 » 编程设计

python之用 Python 抓取文件名的一部分

2025年05月04日11tuyile006

这里是新手。

我刚刚使用 Python/编码工作了几天,但我想创建一个脚本来抓取与特定模式对应的部分文件名,并将其输出到文本文件。

所以就我而言,假设我有四个这样的 .pdf:

aaa_ID_8423.pdf 
bbbb_ID_8852.pdf 
ccccc_ID_7413.pdf 
dddddd_ID_4421.pdf 
 
(Note that they are of variable length.) 

我希望脚本遍历这些文件名,获取“ID_”之后和文件扩展名之前的字符串。

您能指出哪些 Python 模块和可能的指南可以帮助我吗?

请您参考如下方法:

这是一个使用 re 模块的简单解决方案,如其他答案中所述。

# Libraries 
import re 
 
# Example filenames. Use glob as described below to grab your pdf filenames 
file_list = ['name_ID_123.pdf','name2_ID_456.pdf'] # glob.glob("*.pdf")  
 
for fname in file_list: 
    res = re.findall("ID_(\d+).pdf", fname) 
    if not res: continue 
    print res[0] # You can append the result to a list 

下面应该是您的输出。您应该能够使它适应其他模式。

# Output 
123 
456 

祝你好运!