簡體   English   中英

如果已存在同名文件,則將文件移動到文件夾並重命名

[英]move a file to a folder and rename it if a file with the same name already exists

我想將一個或多個文件移動到“存檔”子文件夾中。 但是,我無法處理此“存檔”文件中已存在同名文件的情況。

目前我在文件名(filename.xlsx -> new_filename.xlsx)之前添加了一個字符串(“new_”),但我不喜歡這種做事方式......我寧願這樣重命名它:(文件名.xlsx-> 文件名_1.xlsx)

此外,這種方式不考慮是否必須移動另一個同名文件。

File 1 : src\filename.xlsx ---> src\archive\filename.xlsx (ok)
File 2 : src\filename.xlsx ---> src\archive\new_filename.xlsx (ok)
File 3 : src\filename.xlsx -x-> (problem) 

目標是有這樣的東西:

File 1 : src\filename.xlsx ---> src\archive\filename.xlsx 
File 2 : src\filename.xlsx ---> src\archive\filename_1.xlsx 
File 3 : src\filename.xlsx -x-> src\archive\filename_2.xlsx 

這是我到目前為止所做的:

import os
import shutil
from pathlib import Path

src = r'C:\testonsdestrucs'  

for file in os.listdir(src): 
    full_path = os.path.join(src, file)
    
    if not os.path.isdir(full_path): 
        archive = os.path.join(src, 'Archive') 
        Path(archive).mkdir(parents=True, exist_ok=True)

        files_archive = []
        for file_archive in os.listdir(archive):
            files_archive.append(file_archive)

        if file in files_archive:
            os.rename(full_path,  os.path.join(archive, 'new_' + file) )
        else: 
            shutil.move(full_path, archive )
import os
import shutil                      
from pathlib import Path     

src = r'C:\testonsdestrucs'
for file in os.listdir(src):
    full_path = os.path.join(src, file)             
    if not os.path.isdir(full_path):
        archive = os.path.join(src, "Archive")
        Path(archive).mkdir(parents=True, exist_ok=True)

        files_archive = os.listdir(archive)

        if file in files_archive:
            def rename(old, count):
                new = str(count) + "_" + file
                if new in files_archive:
                    count += 1
                    rename(old, count)
                else:
                    os.rename(full_path, os.path.join(archive, new))

            rename(full_path, 1)
        else:
            shutil.move(full_path, archive)

我已經測試了這段代碼。 它可以正常工作。 但它在前面添加了數字。 如果要在點之前添加數字。 您可以更改重命名規則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM