Note that there are some explanatory texts on larger screens.

plurals
  1. POPython copy files to a new directory and rename if file name already exists
    text
    copied!<p>I've already read <a href="https://stackoverflow.com/questions/10036489/copy-a-file-to-a-new-location-and-increment-filename-python">this thread</a> but when I implement it into my code it only works for a few iterations. </p> <p>I'm using python to iterate through a directory (lets call it move directory) to copy mainly pdf files (matching a unique ID) to another directory (base directory) to the matching folder (with the corresponding unique ID). I started using <code>shutil.copy</code> but if there are duplicates it overwrites the existing file. </p> <p>I'd like to be able to search the corresponding folder to see if the file already exists, and iteratively name it if more than one occurs. </p> <p>e.g.</p> <ul> <li>copy file 1234.pdf to folder in base directory 1234.</li> <li>if 1234.pdf exists to name it 1234_1.pdf,</li> <li>if another pdf is copied as 1234.pdf then it would be 1234_2.pdf.</li> </ul> <p>Here is my code:</p> <pre><code>import arcpy import os import re import sys import traceback import collections import shutil movdir = r"C:\Scans" basedir = r"C:\Links" try: #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: #find the name location and name of files path = os.path.join(root, filename) print path #file name and extension ARN, extension = os.path.splitext(filename) print ARN #Location of the corresponding folder in the new directory link = os.path.join(basedir,ARN) # if the folder already exists in new directory if os.path.exists(link): #this is the file location in the new directory file = os.path.join(basedir, ARN, ARN) linkfn = os.path.join(basedir, ARN, filename) if os.path.exists(linkfn): i = 0 #if this file already exists in the folder print "Path exists already" while os.path.exists(file + "_" + str(i) + extension): i+=1 print "Already 2x exists..." print "Renaming" shutil.copy(path, file + "_" + str(i) + extension) else: shutil.copy(path, link) print ARN + " " + "Copied" else: print ARN + " " + "Not Found" </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload