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 Overflow
๐ŸŒ
DEV Community
dev.to โ€บ hyperkai โ€บ pathmkdirparents-existok-in-python-3hi6
Path.mkdir(parents, exist_ok) in Python - DEV Community
October 14, 2024 - from pathlib import Path p = Path('dir3/dir3_1/dir3_1_1') p.mkdir(parents=True, exist_ok=True) # my_project # |-dir1 # | โ””-dir1_1 # |-dir2 # | โ””-dir2_1 # โ””-dir3 <- Here # โ””-dir3_1 <- Here # โ””-dir3_1_1 <- Here
Discussions

Create file if it doesn't exist, as well as its folders?
Much more readable (imo), and works on any OS: from pathlib import Path output_file = Path("/some/path/file.txt") output_file.parent.mkdir(exist_ok=True, parents=True) output_file.write_text("some text") Would recommend using the following for writing to the file though (handles closing the file for you, stream handling etc.) with open(output_file, 'w') as file: file.write("some text") More on reddit.com
๐ŸŒ r/learnpython
26
64
August 5, 2022
race condition in pathlib mkdir with flags parents=True
BPO 29694 Nosy @arigo, @berkerpeksag, @serhiy-storchaka, @Mariatta, @whitespacer PRs #1089#1126#1127 Files x1.diffx2.diff Note: these values reflect the state of the issue at the time it was migrat... More on github.com
๐ŸŒ github.com
14
March 2, 2017
๐ŸŒ
TradingCode
tradingcode.net โ€บ python โ€บ pathlib-path-mkdir-method
Make new directories with Python's `Path.mkdir()` method
Sometimes we first have to make that path, and then call the mkdir() method to create the directory. Python has several ways to make a path object. One option is to join path components with the overloaded / (division) operator.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ comprehensive-tutorial-on-using-pathlib-in-python-for-file-system-manipulation
How to Use Python's Pathlib (with Examples) | DataCamp
May 22, 2024 - pathlib also offers functionalities for creating and deleting files and directories. Let's see how. The mkdir() method creates a new directory at the specified path. By default, it creates the directory in the current working directory.
Find elsewhere
๐ŸŒ
GitHub
gist.github.com โ€บ e5c6553f239ab6dbf079203a17324be8
Create a folder if not exists with pathlib ยท GitHub
Create a folder if not exists with pathlib. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
Real Python
realpython.com โ€บ lessons โ€บ creating-directories-and-files-recap
Creating Directories and Files (Recap) (Video) โ€“ Real Python
00:00 In the past couple of lessons, you learned how to create directories and files using Pythonโ€™s pathlib module. You used the method .mkdir() to create a directory, and here you also learned about two parameters, one being exist_ok, which you can set to True so that if the directory already exists, Python doesnโ€™t throw an error.
Published ย  December 20, 2022
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ creating-a-directory-and-its-parent-directories-in-python
Creating a Directory and its Parent Directories in Python
August 24, 2023 - Note: Like os.mkdir, os.makedirs will also raise a FileExistsError if the final directory you're trying to create already exists. However, it won't raise an error if the intermediate directories already exist. The pathlib module in Python 3.4 and above provides an object-oriented approach to ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ create file if it doesn't exist, as well as its folders?
r/learnpython on Reddit: Create file if it doesn't exist, as well as its folders?
August 5, 2022 -

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.

๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ pathlib-module
Python's pathlib module - Python Morsels
November 18, 2024 - Python's pathlib module is the tool to use for working with file paths. See pathlib quick reference tables and examples.
๐ŸŒ
Edureka Community
edureka.co โ€บ home โ€บ community โ€บ categories โ€บ python โ€บ how can i safely create a nested directory
How can I safely create a nested directory | Edureka Community
November 19, 2020 - What is the most elegant way to check if the directory a file is going to be written to ... flag for "open", that makes this happen automatically?
๐ŸŒ
Computer Science Atlas
csatlas.com โ€บ python-create-directory
Python 3: Create a Directory with Parents (Like mkdir -p) โ€” Computer Science Atlas
February 8, 2021 - exist_ok=True replicates another feature of mkdir -p, where the command does nothing and does not raise an error if the directory already exists. If you also want to set the directory permissions mode as you create it, you can call the function simply with positional arguments: from pathlib import Path Path( '/tmp/my/new/dir' ).mkdir( 0o755, True, True )
๐ŸŒ
Trey Hunner
treyhunner.com โ€บ 2018 โ€บ 12 โ€บ why-you-should-be-using-pathlib
Why you should be using pathlib
The os module has lots of utilities for working with files and directories: mkdir, getcwd, chmod, stat, remove, rename, and rmdir. Also chdir, link, walk, listdir, makedirs, renames, removedirs, unlink (same as remove), and symlink. And a bunch of other stuff that isnโ€™t related to the filesystems at all: fork, getenv, putenv, environ, getlogin, and system.
๐ŸŒ
GitHub
github.com โ€บ python โ€บ cpython โ€บ issues โ€บ 73880
race condition in pathlib mkdir with flags parents=True ยท Issue #73880 ยท python/cpython
March 2, 2017 - race condition in pathlib mkdir with flags parents=True#73880 ยท Copy link ยท Labels ยท
Author ย  whitespacer
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-os-mkdir-method
os.mkdir() method-Python - GeeksforGeeks
July 11, 2025 - import os path = "C:/Users/GFG0578/Documents/ExistingFolder" try: os.mkdir(path) except OSError as e: print("Error:", e)
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 3 โ€บ pathlib โ€บ index.html
pathlib โ€” Filesystem Paths as Objects
$ python3 pathlib_read_write.py read from open(): 'This is the content' read_text(): 'This is the content' Paths representing directories or symbolic links that do not exist can be used to create the associated file system entries. ... If the path already exists, mkdir() raises a FileExistsError.
๐ŸŒ
Readthedocs
pathlib.readthedocs.io
pathlib โ€” pathlib 1.0.1 documentation
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).
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ os.html
os โ€” Miscellaneous operating system interfaces
February 23, 2026 - The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly created parent directories you can set the umask before invoking makedirs().