0

I have tried this solution:
How to get the latest file in a folder using python

The code I tried is:

import glob
import os

list_of_files = glob.glob('/path/to/folder/**/*.csv') 
latest_file = max(list_of_files, key=os.path.getctime)
print (latest_file)

I received the output with respect to the Windows log of timestamp for the files.

But I have maintained a log separate for writing files in the respective sub-folder.

When I opened the log I see that the last updated file was not what the Python code has specified.

I was shocked as my complete process was depending upon the last file written.
Kindly, let me know what I can do to get the last updated file through Python

I want to read the file which is updated last, but as windows is not prioritizing the updation of the file Last modified, I am not seeing any other way out.

Does anyone has any other way to look out for it?

martineau
  • 119,623
  • 25
  • 170
  • 301
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139

2 Answers2

1

os.path.getctime is the creation time of the file - it seems you want os.path.getmtime which is the modification time of the file, so, try:

latest_file = max(list_of_files, key=os.path.getmtime)

and see if that does what you want.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • Thank you for your answer. I have upvoted you. But please forgive me as I want to give a chance to the new contributor this time. I want to accept Tom's answer as an encouragement. – Jaffer Wilson May 23 '19 at 04:37
1

In linux, os.path.getctime() returns the last modified time, but on windows it returns the creation time. You need to use os.path.getmtime to get the modified time on windows.

import glob
import os

list_of_files = glob.glob('/path/to/folder/**/*.csv') 
latest_file = max(list_of_files, key=os.path.getmtime)
print (latest_file)

This code should work for you.

blackdrumb
  • 310
  • 1
  • 8