用Python获取部分文件名

2024-09-25 18:15:15 发布

您现在位置:Python中文网/ 问答频道 /正文

新来的。

我刚刚使用Python/coding已经有几天了,但是我想创建一个脚本来获取与某个模式对应的部分文件名,并将其输出到一个文本文件。

在我的例子中,假设我有四个这样的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模块和指南可以帮助我吗?


Tags: 文件脚本idthatpdf文件名模式例子
3条回答

如果数字是可变长度的,则需要regex模块“re”

import re

# create and compile a regex pattern
pattern = re.compile(r"_([0-9]+)\.[^\.]+$")

pattern.search("abc_ID_8423.pdf").group(1)
Out[23]: '8423'

Regex通常用于匹配变量字符串。我刚写的regex说:

查找下划线(“\u”),后跟可变位数(“[0-9]+”),后跟字符串中的最后一个句点(“\.[^.]+$”)

这里还有另一种选择,使用re.split(),这可能更接近于您正试图做的事情的精神(尽管使用re.match()re.search()等解决方案同样有效、有用和有指导意义):

>>> import re
>>> re.split("[_.]", "dddddd_ID_4421.pdf")[-2]
'4421'
>>> 

下面是一个使用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

祝你好运!

相关问题 更多 >