Python pathlib 如果目录不存在则创建目录
Python pathlib make directories if they don’t exist
如果我想指定一个路径来保存文件并创建该路径中不存在的目录,是否可以使用 pathlib 库在一行代码中完成此操作?
对,就是Path.mkdir
:
pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)
来自 the docs:
If parents is true, any missing parents of this path are created as
needed; they are created with the default permissions without taking
mode into account (mimicking the POSIX mkdir -p
command).
If parents is false (the default), a missing parent raises
FileNotFoundError
.
If exist_ok is false (the default), FileExistsError
is raised if the
target directory already exists.
If exist_ok is true, FileExistsError
exceptions will be ignored (same
behavior as the POSIX mkdir -p
command), but only if the last path
component is not an existing non-directory file.
这为路径已经存在的情况提供了额外的控制:
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")
添加到 Wim 的回答中。如果您的路径末尾有一个您不想作为目录的文件。
即。
'/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)
如果我想指定一个路径来保存文件并创建该路径中不存在的目录,是否可以使用 pathlib 库在一行代码中完成此操作?
对,就是Path.mkdir
:
pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)
来自 the docs:
If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX
mkdir -p
command).If parents is false (the default), a missing parent raises
FileNotFoundError
.If exist_ok is false (the default),
FileExistsError
is raised if the target directory already exists.If exist_ok is true,
FileExistsError
exceptions will be ignored (same behavior as the POSIXmkdir -p
command), but only if the last path component is not an existing non-directory file.
这为路径已经存在的情况提供了额外的控制:
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")
添加到 Wim 的回答中。如果您的路径末尾有一个您不想作为目录的文件。
即。 '/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)