Подтвердить что ты не робот

Python копирует файлы в новый каталог и переименовывает, если имя файла уже существует

Я уже читал этот поток, но когда я его внедряю в свой код, он работает только для нескольких итераций.

Я использую python для итерации по каталогу (позволяет вызвать его переместить каталог), чтобы копировать в основном файлы PDF (соответствующие уникальному идентификатору) в другой каталог (базовый каталог) в соответствующую папку (с соответствующим уникальным идентификатором). Я начал использовать 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"
4b9b3361

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

Ответ 2

Я бы сказал, что у вас проблема с отступом, по крайней мере, поскольку вы написали ее здесь:

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)

Проверьте это, пожалуйста!

Ответ 3

Я всегда использую отметку времени - поэтому невозможно, что файл уже существует:

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)