Python help- changing output file name if name already exists

5242
14
Jump to solution
03-24-2017 06:47 AM
TheoFaull
Occasional Contributor III

Hi guys and gals,

I have a script which exports a shapefile to a folder. The output file name is 'Properties.shp'. This file is contasntly accessed by a server machine, therefore it has a LOCK file on it.

When I run the script for a second time, it often fails because it detects that and older version of 'Properties.shp' is already sitting in the folder. So when I update this file I have to manually ammend the script to write 'Properties2.shp' as the new output file name to avoid a clash.

Any ideas of how I can get around this? The overwrite = true function won't work as a LOCK file prevents this.

What I want is for the script to rename the output file 'Properties[current_date].shp'

Tags (2)
0 Kudos
14 Replies
TheoFaull
Occasional Contributor III

Thanks again,

But I'm looking for the first 3 characters of the month. I wonder if I can get 'Mar17' for March 2017.

print datetime.datetime.now().strftime("%B%y")

gives me March17...

I need Mar17

0 Kudos
DanPatterson_Retired
MVP Emeritus

you can always improvise if there isn't something in advance...

>>> import datetime
>>> d = datetime.datetime.now()
>>> dd = d.strftime("%d %B %Y").split(" ")
>>> dd
['27', 'March', '2017']
>>> "{}_{}_{}".format(dd[0], dd[1][:3], dd[2])
'27_Mar_2017'
>>> 
TheoFaull
Occasional Contributor III

thank you very much!

I would improvise if I knew how to. I'm still learning the ropes you see...

cheers!

0 Kudos
TheoFaull
Occasional Contributor III

0 Kudos
TedKowal
Occasional Contributor III
movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if os.path.exists(newname):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos