如果我想指定一个保存文件的路径并创建该路径中不存在的目录,是否可以在一行代码中使用pathlib库来执行此操作?
wim*_*wim 37
是的,那是Path.mkdir:
pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)
小智 17
添加到 Wim 的答案。如果您的路径末尾有一个文件,您不希望将其制作为目录。
IE。'/existing_dir/not_existing_dir/another_dir/a_file'
然后使用 PurePath.parents。但好处是,因为 Paths 继承了 Pure Paths 的属性,所以你可以简单地做
filepath = '/existing_dir/not_existing_dir/another_dir/a_file'
pathlib.Path(filepath).parents[0].mkdir(parents=True, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)
Kol*_*ril 13
这为路径已经存在的情况提供了额外的控制:
path = Path.cwd() / 'new' / 'hi' / 'there'
try:
path.mkdir(parents=True, exist_ok=False)
except FileExistsError:
print("Folder is already there")
else:
print("Folder was created")
Run Code Online (Sandbox Code Playgroud)