0

I've searched for an answer for this but the answers still gave me an error message and I wasn't allowed to ask there because I had to make a new question. So here it goes...

I need my python script to use the latest file in a folder.

I tried several things, currently the piece of code looks like this:

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

But the code fails with the following comment:

ValueError: max() arg is an empty sequence

Does anyone have an idea why?

8
  • 3
    Error is telling you that your list_of_files is empty you may need to provide a full path or change the working directory first Commented May 24, 2018 at 8:19
  • Which Python version are you using? And which OS? max (and min) in Python 3 has a way of handling empty lists. But it's cleaner to make sure list_of_files isn't empty before you pass it to max. Commented May 24, 2018 at 8:21
  • Thank you, explaining the error message alone was very helpful. It gives me a clue where to fix things. I'm using python 3.6. The list of files shouldn't be empty and the path is right for as far as I can tell, I'll have to go and figure out why it returns an empty list of files. Thanks! Commented May 24, 2018 at 8:25
  • 2
    print out that variable before preforming max to see if it is what you expect it to be Commented May 24, 2018 at 8:29
  • 1
    @AntonvBR No, that would try to make a key from the max of each individual timestamp, which doesn't make a lot of sense, and max raises TypeError if you try to get the maximum of a number rather than an iterable. Commented May 24, 2018 at 9:30

2 Answers 2

2

It should be ok if the list is not empty, but it seems to be. So first check if the list isn't empty by printing it or something similar.

I tested this code and it worked fine:

import os
import glob

mypath = "C:/Users/<Your username>/Downloads/*.*"

print(min(glob.glob(mypath), key=os.path.getmtime)) 
print(max(glob.glob(mypath), key=os.path.getmtime)) 
Sign up to request clarification or add additional context in comments.

Comments

0

glob.glob has a limitation of not matching the files that start with a .

So, if you want to match these files, this is what you should do - (assume a directory having .picture.png in it)

import glob
glob.glob('.p*') #assuming you're already in the directory

Also, it would be an ideal way to check the number of files present in the directory, before operating on them.

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.