You could try:
p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
fn = "test.txt" # I don't know what is your fn
filepath = p / fn
with filepath.open("w", encoding ="utf-8") as f:
f.write(result)
You shouldn't give a string as path. It is your object filepath which has the method open.
source
Answer from Till on Stack OverflowHow can I check whether the path is a directory?
Does opening a file create its parent directory?
Can I run a directory-creation script more than once?
You could try:
p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
fn = "test.txt" # I don't know what is your fn
filepath = p / fn
with filepath.open("w", encoding ="utf-8") as f:
f.write(result)
You shouldn't give a string as path. It is your object filepath which has the method open.
source
You can directly initialize filepath and create parent directories for parent attribute:
from pathlib import Path
filepath = Path("temp/test.txt")
filepath.parent.mkdir(parents=True, exist_ok=True)
with filepath.open("w", encoding ="utf-8") as f:
f.write(result)
The entire point of mkdir is to create the directory pointed to by its argument. Passing in parents=True creates the parent folders in addition.
Create a new directory at this given path. [...] If parents is true, any missing parents of this path are created as needed; [1]
If you want to ensure the containing directory exists, create the parent of your path:
p = pathlib.Path("D:\scripts\myfolder\logs\somelog.txt")
p.parent.mkdir(parents=True, exist_ok=True)
That's the way Pathlib.mkdir works. It can't tell if the final component should be a file or a directory. parents=True means to create also parents, not only parents. If the final path component is always a file, you could avoid it like
p.parents[0].mkdir(parents=True)
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 -pcommand).If parents is false (the default), a missing parent raises
FileNotFoundError.If exist_ok is false (the default),
FileExistsErroris raised if the target directory already exists.If exist_ok is true,
FileExistsErrorexceptions will be ignored (same behavior as the POSIXmkdir -pcommand), but only if the last path component is not an existing non-directory file.
If your path includes a filename, e.g.
file_path = "/existing_dir/not_existing_dir/another_dir/a_file_name"
Then use file_path.parents[0] or file_path.parent:
from pathlib import Path
file_path = "/existing_dir/not_existing_dir/another_dir/a_file_name"
pathlib.Path(filepath).parent.mkdir(parents=True, exist_ok=True)
Otherwise, you might encounter PermissionError: [Errno 13] Permission denied later on.