Padfoot123
Padfoot123

Reputation: 1117

Filter list of files from directory in python

I have the below files in a directory.

Directory: /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

My expected output is to list only those files which have new and the date should be matching the current date.

Expected output:

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

How to achieve this in python.

Upvotes: 0

Views: 2825

Answers (4)

py_dude
py_dude

Reputation: 832

Probably your solution should look like:

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)

Upvotes: -1

Tzane
Tzane

Reputation: 3472

Pathlib implementation:

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)

Upvotes: 0

Dimas Aps
Dimas Aps

Reputation: 81

you can use 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 ]

Upvotes: 0

rgupta
rgupta

Reputation: 11

You can start by using python's in-build library glob.
Docs: 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)


Upvotes: 1

Related Questions