Python,使用自动重命名选项复制目录

问题描述 投票:1回答:1

SOLVED我是新来的,请耐心等我:)

我搜索了主题,但没找到我想要的东西。

使用Python 2.7,

我想在操作它的内容之前复制一个文件夹,但每次运行代码时都必须重命名重复文件。

(原始文件夹内容每天都会更改,我不想每次在原始文件夹中尝试新内容时更改代码,而且我不想丢失转换后的文件)

我目前的代码:

# renaming files in folder by removing any numbers from the name
# the files are pictures where each picture is a letter a,b,c..
# by removing the numbers, the files will be sorted differently
# which will show a hidden message


import os
import shutil

def magicRename():
    # save the current path
    curPath = os.getcwd()
    # make a copy of the folder before processing the files
    shutil.copytree(r"myFolder", r"myFolder_converted")

    filesList = os.listdir(r"myFolder_converted")
    os.chdir(r"myFolder_converted")
    for fileName in filesList:
        print "The file: [" + fileName + "] renamed to: [" + fileName.translate(None, "0123456789") + "]"
        os.rename(fileName, fileName.translate(None, "0123456789"))
        print "check your files now!"
    # back to old path
    os.chdir(curPath)

# call the function
magicRename()

我想要一种自动重命名的方法,例如:folder_1,folder_2 ......

python-2.7
1个回答
1
投票

那么这样做的方法是计算文件夹的数量:

largest_index = max([0] + [int(f.split('_')[-1]) for f in os.listdir(curPath ) if os.path.isdir(f) and "converted" in f])
new_index = largest_index + 1
new_name = generic_name + '_%d' % new_index

基本上这会查找“myFolder_converted_SOMEINTEGER”形式的文件,找到最大的整数,加1,这就是新名称!

import os
import shutil

def magicRename(folder_to_duplicate):
    # save the current path
    curPath = os.getcwd()
    # make a copy of the folder before processing the files
    all_dirs_in_path = [d for d in os.listdir(curPath ) if os.path.isdir(d)]

    all_converted_dirs_in_path = [d for d in all_dirs_in_path if 'converted' in d]

    largest_index = max([0] + [int(d.split('_')[-1]) for d in all_converted_dirs_in_path])
    new_index = largest_index + 1
    new_name = folder_to_duplicate + '_converted_%d' % new_index
    shutil.copytree(os.path.join(curPath, folder_to_duplicate), os.path.join(curPath, new_name))

    filesList = os.listdir(os.path.join(curPath, new_name))
    os.chdir(os.path.join(curPath, new_name))
    for fileName in filesList:
        print "The file: [" + fileName + "] renamed to: [" + fileName.translate(None, "0123456789") + "]"
        os.rename(fileName, fileName.translate(None, "0123456789"))
        print "check your files now!"
    # back to old path
    os.chdir(curPath)

如果你的文件是这样的:

/directory
    other_directory/

/directory,如果你运行magicRename('other_directory')两次,你会得到:

/directory
    other_directory/
    other_directory_converted_0/
    other_directory_converted_1/

注意:我没有测试过这段代码,这只是一种实现你想要的方法,可能会有一些拼写错误你应该能够自己修复它们


你可以通过计算文件夹的数量来做同样的事情。乍一看,这似乎比查找max和添加1更容易,更直观。但是,如果您决定删除其中一个文件夹,则算法可能会尝试创建一个具有现有名称的新文件夹,从而引发错误。然而,找到最大值确保不会发生这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.