简体   繁体   中英

Python pathlib make directories if they don’t exist

如果我想指定一个路径来保存文件并创建该路径中不存在的目录,是否可以在一行代码中使用 pathlib 库来做到这一点?

Yes, that is Path.mkdir :

pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)

From 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.

This gives additional control for the case that the path is already there:

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")

Adding to Wim's answer. If your path has a file on the end that you do not want made as a directory.

ie. '/existing_dir/not_existing_dir/another_dir/a_file'

Then you use PurePath.parents. But the nice thing is that because Paths inherit the attributes of Pure Paths, then you can simply do

filepath = '/existing_dir/not_existing_dir/another_dir/a_file'
pathlib.Path(filepath).parents[0].mkdir(parents=True, exist_ok=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM