我有一个目录,其中包含日期字符串作为文件名的一部分:
file_type_1_20140722_foo.txt
file_type_two_20140723_bar.txt
filetypethree20140724qux.txt
我需要从文件名中获取这些日期字符串并将它们保存在数组中:
['20140722', '20140723', '20140724']
但是它们可以出现在文件名的不同位置,所以我不能只使用子字符串表示法并直接提取它。在过去,我在Bash中做类似事情的方式是这样的:
date=$(echo $file | egrep -o '[[:digit:]]{8}' | head -n1)
但是I can't use Bash for this because it sucks at math(我需要能够加减浮点数)。我试过glob.glob()
和re.match()
,但都返回空集:
>>> dates = [file for file in sorted(os.listdir('.')) if re.match("[0-9]{8}", file)]
>>> print dates
>>> []
我知道问题是它在寻找8位数长的完整文件名,但我不知道如何让它寻找子字符串。有什么想法吗?
目前没有回答
相关问题 更多 >
编程相关推荐