从python目录中筛选文件列表



我在一个目录中有以下文件:

目录:/home/user_name/files/

pytest.py
jobrun.log
First_new_2021-09-17.log
Last_new_2021-09-17.log
First_new_2021-09-16.log
Last_new_2021-09-16.log

我期望的输出是只列出那些具有new且日期应该与当前日期匹配的文件。

预期输出:

First_new_2021-09-17.log
Last_new_2021-09-17.log

如何在python中实现。

你可以从使用python的内置库glob开始。
文档:https://docs.python.org/3/library/glob.html

import time
from glob import glob
###Since you are working in the same directory, you can simply call glob to find all the files with the extention '.log' by using the wildcard expression '*'.
###Now to get current date you can use time module
today_date = time.strftime("%Y-%m-%d")
file_loc = glob(f'*{today_date}.log')
print(file_loc)

可以使用os

import datetime
import os

thedate  = datetime.datetime.now()    
filelist = [ f for f in os.listdir(mydir) if thedate.strftime("%Y-%m-%d")  in f ]

Pathlib实现:

from pathlib import Path
from datetime import date

folder = Path("/home/user_name/files/")
today = date.today()
match = today.strftime("*new_%Y-%m-%d.log")
matching = [fp for fp in folder.glob(match)]
print(matching)

您的解决方案可能看起来像:

import datetime
import re
import os
today = datetime.date.today() # date today
f_date = today.strftime("%Y-%m-%d") # format the string
pattern = re.compile(fr"[w]+_new_{f_date}.log") # create a pattern to match your files with
result = []
for path, dirs, files in os.walk('/home/user_name/files/'): # iterate over the directories
for file in files: # iterate over each file in the current directory
res = pattern.match(file) # find match
if res := res.group(0): # get name matching the result
result.append(res) # append name to a list of results
print(result)

相关内容

  • 没有找到相关文章

最新更新