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 OverflowCreate file if it doesn't exist, as well as its folders?
Python pathlib make directories if they donโt exist - Stack Overflow
How to subclass pathlib.Path so that it has _flavour and works just like pathlib.Path
OS mkdir not making the directory in try statement
How 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)
I have the following code:
file = open('folder/subfolder/file.txt', 'w')
file.write('hello world')
file.close()
I get an error, however: FileNotFoundError: [Errno 2] No such file or directory
So naturally, I googled how to write to a file, creating it if it doesn't exist. And all the solutions are the same: Do what I did, but it only works if there's no missing subfolders.
How would I create the folder and subfolder (if they don't exist), and then write the file?
I suppose I could split the string, loop through each folder, and test for their existence. But is there a cleaner way to do this? It seems odd python is smart enough to create the file, but not enough to create the directory it's in as well.
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.