[英]Move all files from a directory tree to another directory. Rename if repeated names
我需要獲取給定目錄樹中的所有文件(名為 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)
它加密得很好,然后繼續移動加密文件。 問題是,當它找到並嘗試移動具有現有名稱的文件時,它給了我一個錯誤:
shutil.Error:目標路徑“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 更容易。 它將文件移動到新的目標文件。 新的目標 dir 文件應該是唯一的,您可以使用 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.