首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >追加到现有文件夹名称

追加到现有文件夹名称
EN

Stack Overflow用户
提问于 2015-03-09 12:35:11
回答 3查看 2.6K关注 0票数 0

如何添加到现有文件夹/文件名?

为了清楚起见,我想将"_working"添加到现有的文件夹名称(例如: mxd)中以生成mxd_existing

EN

Stack Overflow用户

发布于 2015-03-09 15:04:50

在重命名单个目录中的多个目录的情况下,您可以使用Python的os.walk

代码语言:javascript
运行
复制
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此命令:

代码语言:javascript
运行
复制
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)
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28935318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档