0

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.

4
  • 2
    Can you please share your progress? What have you tried so far? Commented Sep 17, 2021 at 5:58
  • Look up glob(). Commented Sep 17, 2021 at 6:00
  • What are you struggling with? Getting list of files in a directory? Filtering out files with new in them? Filtering out files with today's date in them? Starting python? Commented Sep 17, 2021 at 6:00
  • I am not able to filter it. I am using os.listdir(directory) Commented Sep 17, 2021 at 6:01

4 Answers 4

1

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)


Sign up to request clarification or add additional context in comments.

Comments

0

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 ]

1 Comment

it will match the file with a name Last_2021-09-17.log and Last_2021-09-17.pdf which is not a valid result
0

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)

Comments

-1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.