简体   繁体   English

如果已存在同名文件,则将文件移动到文件夹并重命名

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

I want to move one or more files into an "archive" subfolder.我想将一个或多个文件移动到“存档”子文件夹中。 However, I'm having trouble handling the case where a file with the same name already exists in this "archive" file.但是,我无法处理此“存档”文件中已存在同名文件的情况。

For the moment I add a string ("new_") before the name of the file (filename.xlsx -> new_filename.xlsx) but I don't like this way of doing things… I would rather rename it like this: (filename.xlsx- > filename_1.xlsx)目前我在文件名(filename.xlsx -> new_filename.xlsx)之前添加了一个字符串(“new_”),但我不喜欢这种做事方式......我宁愿这样重命名它:(文件名.xlsx-> 文件名_1.xlsx)

Moreover, this way does not take into account, if yet another file with the same name have to be moved.此外,这种方式不考虑是否必须移动另一个同名文件。

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) 

The goal is to have something like this:目标是有这样的东西:

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 

Here what I did so far:这是我到目前为止所做的:

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)

I have tested this code.我已经测试了这段代码。 It can work right.它可以正常工作。 But it add the number in the front.但它在前面添加了数字。 If you want to add the number before point.如果要在点之前添加数字。 You can change the rename rules.您可以更改重命名规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM