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
๐ŸŒ
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.
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
Python pathlib make directories if they donโ€™t exist - Stack Overflow
If I wanted to specify a path to ... the pathlib library in one line of code? ... 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 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to subclass pathlib.Path so that it has _flavour and works just like pathlib.Path
This post raises a lot of questions. Firstly, what are you doing in that super call with Path.resolve(path_segments, strict=False)? resolve is an instance methods, and doesn't take a path_segments argument. Did you perhaps mean Path(path_segments).resolve(strict=False)? But even then, why are you trying to pass the resolved path object instead of the original argument? But probably most importantly, why do you think you need to subclass in order to make this work? Much better would be to use composition: create Dir as a standalone class that calls Path internally. More on reddit.com
๐ŸŒ r/learnpython
7
3
July 17, 2024
OS mkdir not making the directory in try statement
Several issues: 1 - the condition if os.mkdir == False: checks if the function itself is false, not the result from previous calls, the function is never False... os.mkdir throws an exception when it fails, so trying to use if conditions to check if it worked will fail. You can use a different function to check if a directory exists, https://www.geeksforgeeks.org/python-os-path-exists-method/ 2 - the check for equality to false needs to be done with == , not is... change this if storage_obj.exists() is False or sync_obj.exists() is False: 3 - your condition will proceed even if one of the directories doesn't exist, then you will try to make both, and one of them will hit an exception. split it... if not storage_obj.exists(): os.mkdir(storage_path) if not sync_obj.exists(): os.mkdir(sync_path) Besides that, your statement isn't clear enough... It always prints false you have 2 print lines that could potentially print false... print("path exists?", storage_obj.exists()) print("Path exists?", sync_obj.exists()) Which one prints false? More on reddit.com
๐ŸŒ r/learnpython
14
1
August 3, 2024
People also ask

How can I check whether the path is a directory?
Use Path(path).is_dir(). Path.exists() also returns True for existing files, so it does not confirm the path is a directory.
๐ŸŒ
askpython.com
askpython.com โ€บ python โ€บ examples โ€บ create-a-directory-in-python
Create a Directory in Python with pathlib - AskPython
Does opening a file create its parent directory?
No. Create the parent path first with Path(file_path).parent.mkdir(parents=True, exist_ok=True), then open the file.
๐ŸŒ
askpython.com
askpython.com โ€บ python โ€บ examples โ€บ create-a-directory-in-python
Create a Directory in Python with pathlib - AskPython
Can I run a directory-creation script more than once?
Yes. Call Path.mkdir() with exist_ok=True when the target may already be a directory. A file at the target path still causes an error.
๐ŸŒ
askpython.com
askpython.com โ€บ python โ€บ examples โ€บ create-a-directory-in-python
Create a Directory in Python with pathlib - AskPython
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ examples โ€บ create-a-directory-in-python
Create a Directory in Python with pathlib - AskPython
3 weeks ago - Use pathlibโ€™s mkdir method to create a directory. Set parents=True when Python must create missing folders.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ learning python โ€บ python's mkdir -p equivalent: creating directories with p...
Python's mkdir -p Equivalent: Creating Directories with pathlib | CodeGym
June 25, 2026 - Both accept exist_ok=True; the semantics match. For new code in 2026, prefer Path.mkdir because it integrates with the rest of pathlib.
๐ŸŒ
DataCamp
datacamp.com โ€บ home โ€บ tutorials โ€บ python โ€บ a comprehensive guide to using pathlib in python for file system manipulation
How to Use Python's Pathlib (with Examples) | DataCamp
May 22, 2024 - The introduction of the pathlib module in Python 3.4 has significantly simplified file system manipulation for developers. By providing an object-oriented approach to handling file paths, pathlib provides a structured and straightforward way to represent file system paths.
Find elsewhere
๐ŸŒ
Python Engineer
python-engineer.com โ€บ posts โ€บ create-nested-directory
How to create a nested directory in Python - Python Engineer
August 7, 2021 - from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True)
๐ŸŒ
PyTutorial
pytutorial.com โ€บ python-pathlib-mkdir-explained
PyTutorial | Python Pathlib mkdir() Explained
March 19, 2025 - To create a directory, first import the Path class from pathlib. Then, call mkdir() on a Path object.
๐ŸŒ
Python Guides
pythonguides.com โ€บ create-a-directory-in-python
How to Make a Directory in Python (os and pathlib)
1 week ago - If a regular file already has that name, Python still raises FileExistsError, because it canโ€™t turn a file into a folder: from pathlib import Path target = Path("photos") print("before:", target.exists()) if not target.exists(): target.mkdir() print("after: ", target.is_dir()) clash = Path("photos.txt") clash.write_text("not a folder", encoding="utf-8") try: clash.mkdir(exist_ok=True) # exist_ok only ignores an existing *folder* except FileExistsError as err: print("FileExistsError:", err.strerror) clash.unlink()
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ pathlib
Python pathlib - working with files and directories in Python with pathlib
January 29, 2024 - We change the current working directory. Note that the directory is changed only inside the Python program. $ change_dir.py Current working directory: C:\Users\Jano\Documents\pyprogs\pathlib Current working directory: C:\Users\Jano\Documents\pyprogs ยท A new directory is created with mkdir.
๐ŸŒ
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
๐ŸŒ
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.

๐ŸŒ
OneUptime
oneuptime.com โ€บ home โ€บ blog โ€บ how to use pathlib for file paths in python
How to Use pathlib for File Paths in Python
January 27, 2026 - pathlib makes file path handling ... .read_text() and .write_text() for simple file operations ยท Use .mkdir(parents=True, exist_ok=True) for safe directory creation ยท...
๐ŸŒ
Computer Science Atlas
csatlas.com โ€บ python-create-directory
Python 3: Create a Directory with Parents (Like mkdir -p) โ€” Computer Science Atlas
February 8, 2021 - from pathlib import Path Path( '/tmp/my/new/dir' ).mkdir( 0o755, True, True ) The 0o at the front of 0o755 means that we intend 755 to be interpreted as an octal number โ€” the format that is commonly used with the chmod command on Linux and other Unix-like systems. If you are using Python 3.4.1 or higher, you can use:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ create-a-directory-in-python
Create a Directory in Python - GeeksforGeeks
4 weeks ago - Import Path from the pathlib module. Create a Path object representing the target directory. Call mkdir() to create the folder.
๐ŸŒ
Codemia
codemia.io โ€บ home โ€บ knowledge hub โ€บ mkdir -p functionality in python
mkdir -p functionality in Python | Codemia
September 23, 2025 - The mkdir -p functionality in Python is readily accessible using both os and pathlib modules, offering flexibility and ease of use. While os.makedirs() offers a straightforward procedural approach, pathlib provides an elegant object-oriented way of handling directories...
๐ŸŒ
Medium
martinxpn.medium.com โ€บ pathlib-the-oop-approach-of-working-with-file-system-in-python-65-100-days-of-python-7dbf85e9cec2
Pathlib โ€” The OOP Approach of Working with File System in Python (65/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - You can also use the mkdir() method to create multiple directories at once. from pathlib import Path # creating a path object path = Path('my_folder') # creating the directory path.mkdir() # creating multiple directories new_path = path / ...