【问题标题】:Python copy files to a new directory and rename if file name already existsPython 将文件复制到新目录并在文件名已存在时重命名
【发布时间】:2013-08-25 08:34:26
【问题描述】:

我已经阅读了this thread,但是当我将它实现到我的代码中时,它只适用于几次迭代。

我正在使用 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"

【问题讨论】:

  • 不,结构不同。例如,movdir 是属性信息的扫描,并已按街道名称排列,pdf 以唯一 ID 命名。所以 C:\Scans\Main St\1234.pdf basedir 是一个新结构,它将通过其唯一 ID 排列特定属性的所有信息。所以 C:\Links\1234 将来可能会有额外的子文件夹,但现在我只是希望将它复制到 C:\Links\1234\1234.pdf

标签: python copy duplicates directory


【解决方案1】:

有时重新开始会更容易......如果有任何错字,我深表歉意,我没有时间彻底测试它。

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 not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1

【讨论】:

  • 感谢您,当我运行此程序时,我收到一条错误消息,提示“ii”未定义。可能是因为我使用的是 2.7(它与 ArcGIS 的 3.x 以上兼容,以后可能会与代码集成)
  • 不,是我搞砸了。它应该是 ii = 1(而不是零,就像我们在另一个答案中所说的那样)而不是 index = 0。
  • 在while循环里面,应该是“if not os.path.exists(new_name)”吧?我的意思是,如果文件不存在,那么我们应该使用索引“ii”来创建它
  • 如果要保留元数据,请考虑 shutil.copy2 docs.python.org/3/library/shutil.html
【解决方案2】:

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

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)

【讨论】:

  • "所以不可能,文件已经存在" ...除非您同时运行代码两次 ;)
  • 虽然这是一个不错的解决方案,但它不能回答我的问题,因为文件中包含包含不同信息的重复文件名,因此需要有一个迭代命名方案......文件的日期无关紧要。
【解决方案3】:

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

import shutil

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

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

【讨论】:

  • 这个答案没有解决主要 OP 的问题,即处理已经存在的文件。您能否详细说明如何检测现有文件并重命名它们?
  • @AlejandroPiad 但它确实满足了我的需求。它可能不是直接作为OP问题的答案,但它确实做得很简单。这样做有好处!至于任何人甚至 OP 都可以理解这个答案并将其作为解决他/她问题的指南。
【解决方案4】:

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

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

应该是:

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

请检查一下!

【讨论】:

  • 很遗憾,它没有改变任何东西。
  • 如果你可以用你所做的更改来更新一点代码,即使它们不起作用,那也很棒。
  • 我认为我的更正中不应该有“不”,对此感到抱歉!我稍后会编辑。
  • 我删除了“不”,它的工作原理!但是,重复文件被命名为 1234_0,我希望它被命名为 1234_1。我认为这与我放置 i+=1 的位置有关。我试着移动它无济于事!
  • 很高兴它成功了!如果你启动 i=0 ,它会首先尝试构建它是正常的。改用 i=1。
【解决方案5】:
import os
import shutil
import glob

src = r"C:\Source"
dest = r"C:\Destination"
par = "*"
i=1
d = []
for file in glob.glob(os.path.join(src,par)):
    f = str(file).split('\\')[-1]
    for n in glob.glob(os.path.join(dest,par)):
        d.append(str(n).split('\\')[-1])
    if f not in d:
        print("copied",f," to ",dest)
        shutil.copy(file,dest)
    else:
        f1 = str(f).split(".")
        f1 = f1[0]+"_"+str(i)+"."+f1[1]
        while f1 in d:
            f1 = str(f).split(".")
            f1 = f1[0]+"_"+str(i)+"."+f1[1]
            print("{} already exists in {}".format(f1,dest))
            i =i + 1
        shutil.copy(file,os.path.join(dest,f1))
        print("renamed and copied ",f1 ,"to",dest)
        i = 1

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
  • 假设我们有两个目录 S 和 D 。如果我们想将文件从 S 复制到 D 并且如果文件,例如要复制的 file.ext 已经存在于 D 中,那么我们将其重命名为 file_1 .ext 并将其复制到 D 类似如果 file_1.ext 存在,我们将其设为 file_2.ext
猜你喜欢
  • 2012-09-29
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2015-10-08
  • 2019-02-04
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
相关资源
最近更新 更多