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?
race condition in pathlib mkdir with flags parents=True
Videos
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.