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

时间:2018-03-19 13:59:32

标签: python-2.7

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 ...

1 个答案:

答案 0 :(得分: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')来自<{p}}

/directory
    other_directory/
    other_directory_converted_0/
    other_directory_converted_1/

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

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