0

I have some code that will find the newest file in a directory and append a time stamp to the file name. It works great as long as there is a file in the directory to rename. If there isn't I am getting:

"ValueError: max() arg is an empty sequence"

Here's my code:

import os
import glob
import datetime
now = datetime.datetime.now()
append = now.strftime("%H%M%S")
newest = max(glob.iglob('1234_fileName*.LOG'), key=os.path.getmtime)
newfile = (append+"_"+newest)
os.rename(newest, newfile)

Any suggestions for simplifying the code would be appreciated as well as explaining how to only run if a "1234_fileName*.LOG" (note the wildcard) file is detected.

What I need this program to do is run periodically (I can use task scheduler for that) and check for a new file. If there is a new file append the hours, minutes and seconds to it's name.

Thanks!

urtonbay
  • 23
  • 5
  • could you edit your title to reflect the question text? If you want to preserve the title then it is a duplicate of: [Check if a file exists using Python](http://stackoverflow.com/q/82831/4279) – jfs Dec 23 '14 at 00:18
  • related: [Check the permissions of a file in python](http://stackoverflow.com/q/27434643/4279). – jfs Dec 23 '14 at 00:23

3 Answers3

3

You could use glob.glob() that returns a list instead of glob.iglob() that returns an iterator:

files = glob.glob('1234_fileName*.LOG')
if files:
   newest = max(files, key=os.path.getmtime)
   newfile = append + "_" + newest
   os.rename(newest, newfile)

Both glob() and iglob() use os.listdir() under the hood so there is no difference for a single directory.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
2

max() is complaining that you're asking for the largest of 0 items, and throwing a ValueError. You'll have to catch it. This will continue to throw any IOErrors that might occur:

import os, glob, datetime

try:
    app = datetime.datetime.now().strftime("%H%M%S")
    newest = max(glob.iglob("1234_filename*.LOG"), key=os.path.getmtime)
    newfile = (app + "_" + newest)
    os.rename(newest, newfile)
except ValueError:
    pass
Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
1

os.access allows you to check access rights before operations. An example is right under the link.

Also, it's fine to just do things inside a try .. except IOError.

9000
  • 39,899
  • 9
  • 66
  • 104
  • Plus one for `try`-`catch`, that's allegedly more Pythonic and it seems as if it would be [more resistant to race conditions](http://blog.rodneyrehm.de/archives/12-Improving-Disk-IO-in-PHP-Apps.html). – Waleed Khan Dec 23 '14 at 00:11
  • how `os.access()` may help to avoid `"ValueError: max() arg is an empty sequence"` in this case? – jfs Dec 23 '14 at 00:18
  • @J.F.Sebastian: Sorry, I was answering the title question, "How can I check to see if a file exists before proceeding using Python", not the implied question "why this code fails". – 9000 Dec 23 '14 at 16:18