如何添加到现有文件夹/文件名?
为了清楚起见,我想将"_working"添加到现有的文件夹名称(例如: mxd)中以生成mxd_existing。
发布于 2015-03-09 15:04:50
在重命名单个目录中的多个目录的情况下,您可以使用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模块。这可以让您的工作更快、更简单,而不是手动迭代所有文件。LIke此命令:
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)https://stackoverflow.com/questions/28935318
复制相似问题