检查文件名python3中的日期是否相同

2024-09-29 19:19:50 发布

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

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

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

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

有很多不同日期的文件,我想看看有多少文件是在同一个日期出现的。你知道吗

谢谢!你知道吗


Tags: 文件namein目录txtforifos
3条回答

为此,可以使用python的regex和Counter类:

import re
from collections import Counter

files = ['foo161108part.txt','baarr161108part2.txt','python141106part2.txt']

dates = []
for f in files:
    m = re.match(r"^.*(\d{6}).*\.txt$", f)
    if m:
        dates.append(m.group(1))
print dates
print Counter(dates)

输出:

['161108', '161108', '141106']
Counter({'161108': 2, '141106': 1})

如果目的只是比较文件的内容,那么理想的方法是使用^{}模块。此模块提供^{}方法,该方法:

Compare the files named f1 and f2, returning True if they seem equal, False otherwise.

示例:

>>> import filecmp
>>> filecmp.cmp('undoc.rst', 'undoc.rst') 
True
>>> filecmp.cmp('undoc.rst', 'index.rst') 
False

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

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

相关问题 更多 >

    热门问题