Python 将所有文件从目录树移动到另一个目录。如果名称重复,请重命名

Python 将所有文件从目录树移动到另一个目录。如果名称重复,请重命名,python,file,rename,move,shutil,Python,File,Rename,Move,Shutil,我需要获取给定目录树中的所有文件(名为Temp的文件夹和包含更多子目录和文件的子目录…)对它们进行加密,并将所有内容移动到一个唯一的目录(名为Temp2的文件夹,没有子目录)。如果有重复的名称,我想将名称更改为text.txt-->text(1.txt),然后继续移动重命名的文件 这就是我目前的情况: bufferSize = 64 * 1024 password1 = 'password' print('\n> Beginning recursive encryption...\n\n

我需要获取给定目录树中的所有文件(名为Temp的文件夹和包含更多子目录和文件的子目录…)对它们进行加密,并将所有内容移动到一个唯一的目录(名为Temp2的文件夹,没有子目录)。如果有重复的名称,我想将名称更改为text.txt-->text(1.txt),然后继续移动重命名的文件

这就是我目前的情况:

bufferSize = 64 * 1024
password1 = 'password'

print('\n> Beginning recursive encryption...\n\n')
for archivo in glob.glob(sourcePath + '\\**\*', recursive=True):
   fullPath = os.path.join(sourcePath, archivo)
   fullNewf = os.path.join(destinationPath, archivo + '.aes')

   if os.path.isfile(fullPath):
      print('>>> Original: \t' + fullPath + '')
      print('>>> Encrypted: \t' + fullNewf + '\n')
      pyAesCrypt.encryptFile(fullPath, fullNewf, password1, bufferSize)
      shutil.move(fullPath + '.aes', destinationPath)
它加密得很好,然后继续移动加密文件。问题是,当它查找并试图移动一个具有现有名称的文件时,它会给我一个错误:

错误:目标路径 “E:\AAA\Folder\Folder\Temp2\Text.txt.aes”已存在

因此,我需要知道如何在移动文件的过程中重命名具有重复名称的文件,然后再移动它们,但不知道如何继续

def make_unique_filename(file_path):
    duplicate_nr = 0
    base, extension = os.path.splitext(file_path)
    while os.path.exists(file_path):
        duplicate_nr += 1
        file_path = f'{base}({duplicate_nr}){extension}'

    return file_path
然后

os.rename(src_file_path, make_unique_filename(dest_file_path))
shutil.move移动到目录目标

使用os.rename更容易。 它将文件移动到新的目标文件。新的目标目录文件应该是唯一的,这可以通过make_unique_filename实现

这个代码现在正在为我工作。您的os.path.join存在另一个问题。这是没有必要的。glob.glob已返回完整路径

import pyAesCrypt
import os
import glob

sourcePath = r'E:\test aes\src'
destinationPath = r'E:\test aes\dst'

bufferSize = 64 * 1024
password1 = 'password'

def make_unique_filename(file_path):
    duplicate_nr = 0
    base, extension = os.path.splitext(file_path)
    while os.path.exists(file_path):
        duplicate_nr += 1
        file_path = f'{base}({duplicate_nr}){extension}'

   return file_path


for archivo in glob.glob(sourcePath + '\\**\*', recursive=True):
    fullPath = archivo
    fullNewf = archivo + '.aes'

    if os.path.isfile(fullPath):
        print('>>> Original: \t' + fullPath + '')
        print('>>> Encrypted: \t' + fullNewf + '\n')
        pyAesCrypt.encryptFile(fullPath, fullNewf, password1, bufferSize)

        destination_file_path = os.path.join(destinationPath, os.path.split(fullNewf)[1])
        destination_file_path = make_unique_filename(destination_file_path)
        print(destination_file_path)
        os.rename(fullNewf, destination_file_path)

嘿,谢谢你的回答。我试过这个代码,但它不符合我的要求。它复制、加密和重命名每个添加(1)的文件,并且不会将它们移动到destinationPath。粘贴上面问题中的代码,我会看一看。我上面的代码现在正在工作。您使用的路径存在问题/混乱。为了清晰起见,为了打印它,我将目标文件路径的制作进行了拆分。