python重命名文件或目录_Python将文件复制到新目录,如果文件名已经存在,则重命名...

我已经读过this thread,但是当我在代码中实现它时,它只在几个迭代中起作用。

我使用python遍历一个目录(我们称之为move directory),主要将pdf文件(匹配唯一ID)复制到另一个目录(基本目录)和匹配的文件夹(具有相应的唯一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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值