How to check if a file exists and if so rename it in python
Question: I am looking for a more pythonic way to do what my code does currently. I'm
sure there is a better way to do this. I would like to search up until
filename-10, and if that exists create a file called filename-11.

If you can help that would be great.

EDIT: 9/1/14 9:46 PM

    
    
    import re
    import os
    f=open('/Users/jakerandall/Desktop/Data Collection Python/temp.cnc', 'r')
    text = re.search(r"(?<!\d)\d{4,5}(?!\d)", f.read())
    JobNumber = text.string[text.start():text.end()]
    
    
    if os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-10.cnc" % JobNumber):
        f=open("/Users/jakerandall/Desktop/Data Collection Python/%s-11.cnc"  % JobNumber, 'w+b')
        f.close()
        print '1'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-9.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-10.cnc' % JobNumber, 'w+b')
        f.close()
        print '2'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-8.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-9.cnc' % JobNumber, 'w+b')
        f.close()
        print '3'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-7.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-8.cnc' % JobNumber, 'w+b')
        f.close()
        print '4'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-6.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-7.cnc' % JobNumber, 'w+b')
        f.close()
        print '5'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-5.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-6.cnc' % JobNumber, 'w+b')
        f.close()
        print '6'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-4.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-5.cnc' % JobNumber, 'w+b')
        f.close()
        print '7'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-3.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-4.cnc' % JobNumber, 'w+b')
        f.close()
        print '8'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-2.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-3.cnc' % JobNumber, 'w+b')
        f.close()
        print '9'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s-1.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-2.cnc' % JobNumber, 'w+b')
        f.close()
        print '10'
    elif os.path.isfile("/Users/jakerandall/Desktop/Data Collection Python/%s.cnc" % JobNumber):
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s-1.cnc' % JobNumber, 'w+b')
        f.close()
        print '11'
    else:
        f=open('/Users/jakerandall/Desktop/Data Collection Python/%s.cnc' % JobNumber, 'w+b')
        f.close()
        print '12'
    f.close()
    


Answer: How about something simpler:

    
    
    import glob
    
    file_directory = '/Users/jakerandall/Desktop/Data Collection Python/'
    files = glob.glob('{}{}*.cnc'.format(file_directory, JobNumber))
    

Now `files` will be a list of file names that actually exist in the directory
and match your pattern.

You can check the length of this list, and then:

  1. If its empty, create the first file, which is just `'{}.cnc'.format(JobNumber)`.
  2. If the length of the list is equal to 11, you need to create file number 11 (because the pattern will match the first file, the one without any `-`, so a length of 11 means the last file is `-10.cnc`).
  3. Otherwise, the file you want is 1-the length of the list. So if the list has 5 items, it means the last file is `-4.cnc` (because the pattern will also match the very first file).

You'll still need to see if you can open them, because the user running the
Python script may not have sufficient permissions.

Here is an example putting all that together:

    
    
    import glob
    
    file_directory = '/Users/jakerandall/Desktop/Data Collection Python/'
    files = glob.glob('{}{}*.cnc'.format(file_directory, JobNumber))
    
    # Start by assuming there are no files:
    filename = '{}.cnc'.format(JobNumber)
    if len(files) <= 11:
       # If there are less than 11 files, we need
       # to use the existing file, and overwrite it
       # If there are 4 files, in the directory, our
       # list will have a length of 5:
       # The original file, and then four files from -1, to -4
       # In this case, we want to use file 4, which is 1 less than
       # the length of the list:
       filename = '{}-{}.cnc'.format(JobNumber, len(files)-1)
    else:
       # If we reach this point, it means
       # there were more than 10 files that match the
       # pattern. We want to use the next file,
       # which is next number higher, which is also the length
       # of the list, since it will include the first file.
       # So if the last file is -20, the list will have 20 files (from -1, to -20)
       # plus the original file, which has no - in the filename, giving
       # a length of 21, which also happens to be the number of the file
       # we want to create :)
       filename = '{}-{}.cnc'.format(JobNumber, len(files))
    
    # Now, try to create the file
    try:
       f = open(filename, 'w+b')
    except IOError:
       print('Cannot create {}, check permissions?'.format(filename)) 
    

