附加到现有文件夹名称

时间:2015-03-09 04:35:11

标签: python file-rename

如何添加现有的文件夹/文件名? 为了澄清,我想将"_working"添加到现有文件夹名称(例如:mxd)以生成mxd_existing

3 个答案:

答案 0 :(得分:1)

import os
old_name = 'mxd'
new_name = old_name + '_working'
os.rename(old_name, new_name)

答案 1 :(得分:1)

如果在一个目录中重命名多个目录,您可以使用Python os.walk

from os import walk
from os.path import join, isdir, abspath
from shutil import move

base_directory = "." # Directory in which we need to modify the dir names
base_directory = abspath(base_directory) # To make the base_directory an absolute path
# Above is needed for shutil.move to work

all_child_directories = next(walk(base_directory))[1]
for child_dir in all_child_directories:
    new_name = child_dir + "_working"
    if not isdir(join(base_directory, new_name)): 
    # shutil.move cannot move if the existing directory already exists
        move(join(base_directory, child_dir), join(base_directory, new_name))

这可能看起来很多但绝对不多。如上面的链接所示,os.walk将为生成器提供目录名,子目录和目录中的文件作为元组。这里我们只需要元组的第二个元素,因此我们选择1。现在我们只是遍历子目录列表并使用新名称移动整个目录。

在这里,您可以添加代码要满足的任何条件。但是,如果您只想要一些名称在基本目录中具有许多子目录的模式的目录,那么您应该查找glob模块。这可以使您的工作更快更简单,而不是手动迭代所有文件。喜欢这个:

from glob import glob
from shutil import move
from os.path import join, isdir, abspath

base_directory = "."
base_directory = abspath(base_directory)
pattern_name = "project" # part of the directory name
for dir_with_pattern in glob(join(base_directory, pattern_name)):
    new_name = dir_with_pattern + "_existing"
    if not isidr(new_name):
        move(dir_with_pattern, new_name)

答案 2 :(得分:0)

您可以将其作为要更改的文件夹中的脚本运行:

import os
folder_name = os.getcwd() + "_working"
os.rename(os.getcwd(), folder_name)

如果您收到权限被拒绝错误,则表示您不应该更改您所在文件夹的名称,但如果您确实要更改名称,请使用sudo python运行脚本

相关问题