我已经阅读了这篇文章,但是当我把它应用到我的代码中时,它只能运行几次。
我正在使用Python遍历一个目录(假设称为"移动目录"),将主要匹配唯一ID的PDF文件复制到另一个目录(基本目录)的相应文件夹(具有相应的唯一ID)。我最初使用shutil.copy
进行复制,但是如果存在重复文件,它会覆盖现有文件。
我想能够搜索相应的文件夹以查看文件是否已经存在,并在出现多个文件时迭代地对其命名。
例如:
- 将文件1234.pdf复制到基本目录中的文件夹1234中。
- 如果1234.pdf已经存在,则将其命名为1234_1.pdf,
- 如果另一个PDF被复制为1234.pdf,则它将被命名为1234_2.pdf。
以下是我的代码:
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"
filename_fix_existing(filename)
。 - Grijesh Chauhan