- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在清理一些文件夹。给定文件结构:
a/1
a/2
a/3
a/3/3_1
a/3/3_2
我想通过在第一级文件夹前添加父文件夹前缀来重命名第一级文件夹仅当它不包含任何子目录时,即输出:
a/a-1
a/a-2
a/3
a/3/3_1
a/3/3_2
我有以下代码来执行此操作:
root_dir = "./"
parent_path = os.path.abspath(root_dir)
parent_folder_name = os.path.abspath(root_dir).split('/')[-1]
dirs = []
for entry in os.listdir(root_dir):
absolute_path = parent_path + "/" + entry
if os.path.isdir(absolute_path) and entry[0] != ".":
dirs.append(absolute_path)
for first_level_dir in dirs:
# travers each directory in root directory
skip_dir = False
subdirs = os.walk(first_level_dir).next()[1]
if len(subdirs) == 0
volume_folder_name = first_level_dir.split("/")[-1]
new_dir_name = (parent_path + "/" + parent_folder_name + "-" + volume_folder_name)
os.rename(first_level_dir, new_dir_name)
代码可以工作,但看起来非常冗长。有没有更Pythonic的方法来做到这一点?
最佳答案
为了使代码更具可读性,请提取 has_subdir()
函数:
from pathlib import Path
def has_subdir(path):
return any(p.is_dir() for p in path.iterdir())
root = Path().resolve()
dirs = [p for p in root.iterdir() if p.is_dir() and not has_subdir(p)]
for oldpath in dirs:
newname = '{}-{}'.format(oldpath.parent.name, oldpath.name)
oldpath.rename(oldpath.with_name(newname))
关于python - 更多Python主义 : prefix subdirectory with parent folder name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27683406/
我有 table item与 item_id, item_title, item_description, item_created, item_approved 。我也有一张 table artic
我需要使用 Symfony2 删除带有 Doctrine 的集合。 所以,我检索所有这样的对象: $comments = $em->getRepository('ProjectApplicationB
什么是神奇的$Facebookism-types in flow我该如何使用它们? flow repo中有5种这样的类型: https://github.com/facebook/flow/searc
如何使用学说2中的mysql的LEFT函数?查询应该类似于 SELECT LEFT(myfield, N) FROM mytable 最佳答案 match(Lexer::T_IDENTIFIER);
我最近将一个项目从 GCC 移植到 clang(我在其中修复了一些 C GNU 主义)。这让我开始思考:存在哪些 C GNU 主义(GCC 支持的 C 语言的扩展,未标准化)?哪里有完整的列表? 最佳
所以我得到了一个 ZF2 应用程序,在我拥有的 InputFilter 中得到了一个 Form 和一个 InputFilter: $this->add( array(
我正在尝试使用原始查询显示表“Post”的某些字段: $connection = $em->getConnection(); $statement = $connection->prepare
我有两个实体,我正在尝试对其应用 OneToMany/ManyToOne 关系(一个游戏有多个 GameContent)。 游戏 /** * @ORM\OneToMany(targetEntity=
我已经被困在这个问题上有一段时间了: 我想通过使用 DESC 对“datevalidite”列进行排序,从表“seuils”中提取值“points”。 SQL 工作正常: SELECT points
我是一名优秀的程序员,十分优秀!