Python将文件复制到新目录,并重命名文件名是否已存在

GIS*_*Kid 29 python directory copy duplicates

我已经阅读过这个帖子,但是当我将它实现到我的代码中时,它只适用于几次迭代.

我正在使用python迭代目录(让我们称之为移动目录)将主要是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"
Run Code Online (Sandbox Code Playgroud)

Jbl*_*sco 23

有时它更容易重新开始......如果有任何拼写错误我道歉,我没有时间对它进行彻底的测试.

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(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1
Run Code Online (Sandbox Code Playgroud)

  • 不,这是我搞砸了.它应该是ii = 1(而不是零,就像我们在另一个答案中所说的那样)而不是index = 0. (3认同)

use*_*811 16

我总是使用时间戳 - 因此不可能,文件已经存在:

import os
import shutil
import datetime

now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")

src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
Run Code Online (Sandbox Code Playgroud)

  • “因此不可能,因为该文件已经存在”……除非您同时运行两次代码;) (4认同)

Ale*_*anu 13

对我来说 shutil.copy 是最好的:

import shutil

#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)
Run Code Online (Sandbox Code Playgroud)

您可以根据需要更改文件的路径。

  • 这个答案没有解决主要OP的问题,即处理已经存在的文件。您能否详细说明如何检测现有文件并重命名它们的更完整答案? (3认同)

Jbl*_*sco 5

我会说你有一个缩进问题,至少在你在这里写的时候:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)
Run Code Online (Sandbox Code Playgroud)

应该:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)
Run Code Online (Sandbox Code Playgroud)

看看这个,拜托!