gpt4 book ai didi

python - 检查文件的名称是否具有相同的日期,Python 3

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:03 25 4
gpt4 key购买 nike

我有一些文件保存了日期,例如foo161108part.txtbaarr161108part2.txtpython141106part2.txt

到目前为止,我已经列出了目录:

directoryFiles = []
for name in os.listdir(os.getcwd()):
if name.endswith('.txt'):
files.append(name)
print(files)

有很多不同日期的不同文件,我想看看有多少文件在同一日期出现。

谢谢!

最佳答案

如果日期部分是在文件名中搜索的关键部分,请考虑以下方法:

import re

counts = {}
pattern = re.compile(r'^.*(\d{6}).*?$')

for f in os.listdir('text_files'):
m = re.match(pattern, f)
if m:
date_value = m.group(1)
counts[date_value] = counts[date_value]+1 if counts.get(date_value) else 1

print(counts)

输出:

{'161108': 2, '141106': 1}

对于正则表达式:

using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program

关于python - 检查文件的名称是否具有相同的日期,Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com