如果文件名已经存在,Python 将文件复制到新目录并重命名

Python copy files to a new directory and rename if file name already exists(如果文件名已经存在,Python 将文件复制到新目录并重命名)
本文介绍了如果文件名已经存在,Python 将文件复制到新目录并重命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I've already read this thread but when I implement it into my code it only works for a few iterations.

我正在使用 python 遍历一个目录(我们称之为移动目录),主要将 pdf 文件(匹配唯一 ID)复制到另一个目录(基本目录)到匹配文件夹(具有相应的唯一 ID).我开始使用 shutil.copy 但如果有重复,它会覆盖现有文件.

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 shutil.copy but if there are duplicates it overwrites the existing file.

我希望能够搜索相应的文件夹以查看该文件是否已存在,如果出现多个,则对其进行迭代命名.

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.

例如

  • 将文件 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"

推荐答案

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

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

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

这篇关于如果文件名已经存在,Python 将文件复制到新目录并重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)