-1

I want to access a folder which is created automatically according to date like for today it will be created '20230222' for tomorrow it will be created as '20230223' in E drive .Inside every folder .txt files are created which I want to access,but I dont want to change the path everyday.I want to pick the latest folder which will be created according to date and access the .txt files inside them

I tried this:

import os
import glob
path='E:/20230222/*'
files_list=glob.glob(path)
latest_file=max(files_list,key=os.path.getctime)
print(latest_file)

This returns the latest .txt file which is created inside today's folder[20230222] But I want to set path in a way that it should directly select the folder whenever it is created according to that day's date, like for tomorrow it should directly select [20230223] Folder after it is formed in E drive

Beast
  • 23
  • 4
  • 2
    So your question is not "Get the latest file in a folder" but actually "how to convert the current date into a string of the form YYYYMMDD" - right? – Mike Scotty Feb 22 '23 at 10:19
  • Does this answer your question? [How to convert integer into date object python?](https://stackoverflow.com/questions/9750330/how-to-convert-integer-into-date-object-python) – meshkati Feb 22 '23 at 10:32
  • No I want to get the latest text file inside the particular folder but I want to set a path in a way that I dont have to change it everyday it should directly select that folder everyday and get the latest txt file inside that folder – Beast Feb 22 '23 at 10:48
  • The title reads: You already have a folder and need to select the latest text file. The body reads: You want to select a folder that is named after today's date in a certain format. I would say that they're two separate problems and should be treated as such. – Standard_101 Feb 22 '23 at 13:37

2 Answers2

1

You can do something like this using pathlib:

import pathlib

root = pathlib.Path('E')
# find last folder:
folder = sorted([f for f in root.glob('*') if f.is_dir()], key=lambda x: x.name, reverse=True])
if len(folder) > 0:
    folder = folder[0]
else:
    print('No folder in E drive')
    # you should exit the script or function here
files_list = folder.glob('*')
latest_file=max(files_list,key=os.path.getctime)
3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
1

You need to get today's date in the required format [YYYYMMDD]. One of the ways to do so would be to use the datetime library.

>>> from datetime import datetime
>>> date = datetime.today().strftime('%Y%m%d')
>>> date
'20230222'

Your path is then simply:

path=f'E:/{date}/*'
Standard_101
  • 325
  • 4
  • 14