Not really, as you can see in the pathlib module exist 2 types of path classes:

  • pure path classes {PurePath, PurePosixPath, PureWindowsPath}
  • concrete path classes {Path, PosixPath, WindowsPath}.

Parameters of theses classes constructors will be just *pathsegments.

And if you look at the available read/write methods (read_text/read_bytes and write_text/write_bytes) you'll also see mode won't be available neither

So, as you've already discovered, the only way you can use mode with these pathlib classes is by using open method, ie:

with my_path.open("a") as f:
    f.write("...")

This is by design and that way the pathlib classes have become really "clean". Also, the above snippet is already canonical so it can't be simplified any further. You could use open method outside the context manager though:

f = my_path.open("a")
f.write("...")
Answer from BPL on Stack Overflow
Top answer
1 of 7
38

Not really, as you can see in the pathlib module exist 2 types of path classes:

  • pure path classes {PurePath, PurePosixPath, PureWindowsPath}
  • concrete path classes {Path, PosixPath, WindowsPath}.

Parameters of theses classes constructors will be just *pathsegments.

And if you look at the available read/write methods (read_text/read_bytes and write_text/write_bytes) you'll also see mode won't be available neither

So, as you've already discovered, the only way you can use mode with these pathlib classes is by using open method, ie:

with my_path.open("a") as f:
    f.write("...")

This is by design and that way the pathlib classes have become really "clean". Also, the above snippet is already canonical so it can't be simplified any further. You could use open method outside the context manager though:

f = my_path.open("a")
f.write("...")
2 of 7
12

There is no "append mode" for write_text, nor is there a corresponding append_text method. If you need it, you can write a function for it yourself pretty easily:

def append_text(path, text, encoding=None, errors=None):
   with path.open("a", encoding=encoding, errors=errors) as f:
       f.write(text)

You might be wondering why such a thing isn't built directly into pathlib as a method. One reason is precisely because it is so easy to implement yourself that it's not really worth adding, but clearly that's not the whole story, because read_text and write_text would be similarly easy to implement yourself.

I think a major reason why pathlib.Path objects don't (and, indeed, shouldn't) have a append_text method is because it creates a hole for inexperienced users to fall into, which is a huge sin in API design.

Specifically, the hole I'm referring to is using append_text on the same file repeatedly in a loop. Because you're continually opening and closing the file, it is slow. Plus, doing so many unnecessary writes is probably not great for the health of your hard drive.

Worse, because the program will actually behave correctly (e.g. the file will have the contents they intended), they may not even notice anything is wrong, because they don't necessarily have a mental gauge on how long writing to a file "should" take.

This is exactly the sort of code a naïve programmer would write:

from pathlib import Path

N = 100

path = Path("numbers.txt")

path.write_text(f"{N}\n")
for i in range(N):
    path.append_text(f"{i}\n")
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths
Create a file at this given path. If mode is given, it is combined with the process’s umask value to determine the file mode and access flags. If the file already exists, the function succeeds when exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised. ... The open(), write_text() and write_bytes() methods are often used to create files.
🌐
Reddit
reddit.com › r/learnpython › ‘with’ statement vs ‘pathlib’ method for opening files
r/learnpython on Reddit: ‘With’ statement vs ‘pathlib’ method for opening files
April 18, 2024 -

Hi, in the online Python course im following, the instructor used a “with … as … “ statement for opening a file so he could iterate with a for loop later. Without much further explanation.

I like to learn by building a strong foundation, so if i see something i don’t know yet, or want to know more about, i look it up in the book ‘python crash course 3rd edition’.

To my surprise and great confusion, there is nothing about ‘with’ statements in the book. After some research i found that that method was used and explained in the 2nd edition, but in the 3rd edition it’s completely replaced by using the ‘pathlib’ method. This method seems easy and straightforward, but since it takes the whole content of a file as one single string, and i want to iterate over separate lines with a for loop, i need to cut it up first using ‘.splitlines’. That’s explained pretty well in the 3rd edition, so no problem there.

But i do have some questions now: Why the change to pathlib? Should i just use this method from now on, and forget about the ‘with’ statement stuff? What method of the two do you guys prefer?

Top answer
1 of 5
9
There is no pathlib method for opening files. pathlib is, as the name suggests, a library for dealing with paths. It is not in any way an alternative to opening files inside a context manager (with), which is responsible for doing things like cleaning up file handles when you are finished with them. In fact the two work together well, for example: directory = pathlib.Path('dir') file_path = directory / "filename" with file_path.open() as f: ... Maybe you should post an example of what you think has changed?
2 of 5
4
I would always use a with statement when opening files. What the with statement does is as follows: with thing_that_opens_context_manager() as name: do_stuff ... A context manager is a python object with methods called __enter__ and __exit__ which allocate and deallocate resources respectively. The way the with statement works is that it calls enter at the start, runs whatever is in the block (do_stuff) and then runs __exit__ irrespective of whether the code failed or errored out. Basically, it guarantees that __exit__ is always called. __enter__ contains code that allocates you resources, __exit__ contains code that cleans them up. The as name bit binds whatever the __enter__ function returns to the variable name. This basically gives you an interface into interacting with whatever you're managing. It's a bit case-to-case though so might not be used the same way library to library. In your case, that means that it guarantees that file handles opened will always be closed. If you use a database connection (with sqlalchemy, say) it guarantees that open database connection pools are properly closed after being opened. My suggestion is that you use both a with statement and pathlib together because Path('...').open() returns an object that is a context manager, so can also be used in a with statement. It's a good practice to use with whenever you have an object that does any form of clean-up whatsoever. It'll remove headaches down the line. TL;DR: pathlib and with are not mutually exclusive and you should use with whenever you're handling files unless you have a very good reason not to.
🌐
Mopicmp
mopicmp.github.io › python-pathlib › path-write-text.html
Path.write_text - Python Pathlib | BetterDocs
completed_queries=data.get("completed_queries", []), ) def save(self, path: Path): """Save state to JSON file.""" path.write_text(json.dumps(self.to_dict(), indent=2)) @classmethod def load(cls, path: Path) -> FetchState: """Load state from JSON file.""" if path.exists(): return cls.from_dict(json.loads(path.read_text())) return cls() class GitHubClient: """Client for GitHub REST API with Code Search.""" CODE_SEARCH_URL = "https://api.github.com/search/code" REPOS_URL = "https://api.github.com/repos" def __init__(self, token: str): self.token = token self.client = httpx.Client( headers={ ... Our comprehensive course Python Everyday Automation covers everything from basics to advanced patterns with hands-on projects.
🌐
Python.org
discuss.python.org › python help
`pathlib.Path.write_text` data loss on full disk - Python Help - Discussions on Python.org
September 4, 2023 - Let’s say I have a survey application where after each action a form is serialized and saved as a json file. python json_path.write_text( json.dumps( { "answers": answers } ) ) Today I got a report where user data was lost (0 bytes file) because disk got full.
🌐
Inspired Python
inspiredpython.com › tip › python-pathlib-tips-reading-from-and-writing-to-files
Python Pathlib Tips: Reading from and Writing to Files • Inspired Python
Inspired Python · ◆◆◆ · >>> from pathlib import Path >>> p = Path('/tmp/inspiredpython.txt') >>> p.write_text('Hello from Inspired Python') >>> p.read_text() 'Hello from Inspired Python' “ · You can use the pathlib module’s Path() class to read and write to files directly, circumventing the need for open() if you don’t need access to the file object.
🌐
PyTutorial
pytutorial.com › python-pathlib-write_text-explained
PyTutorial | Python Pathlib write_text() Explained
March 22, 2025 - The write_text() method is part of the Pathlib module. It writes a string to a file. If the file doesn't exist, it creates it.
Find elsewhere
🌐
Techie Delight
techiedelight.com › home › python › write to a file in python
Write to a file in Python | Techie Delight
July 7, 2026 - Additionally, if you need to read text from the file, use the 'a+' mode. With Python 3.4, you can also use the pathlib module. The Path.write_text() function opens the file in text mode, write data to it, and close the file.
🌐
Mimo
mimo.org › glossary › python › pathlib
Mimo: The coding platform you need to learn Web Development, Python, and more.
The module pathlib Python provides comes with read_text() and write_text() methods for basic file operations.
🌐
Basicexamples
basicexamples.com › example › python › pathlib-path-write-text
Basic example of Python function pathlib.Path.write_text()
Simple usage example of `pathlib.Path.write_text()`. The `pathlib.Path.write_text()` function is a convenient method in Python's `pathlib` module that allows you to write text content to a file. It creates a new file or overwrites the existing one with the specified text.
🌐
GitHub
github.com › python › cpython › issues › 149611
Path.write_text() and Path.write_bytes() don't explain their return value · Issue #149611 · python/cpython
May 9, 2026 - https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_text shows examples of returning an integer, but there is no mention of what the value represents. (It's the number of characters or bytes written). gh-149611: Explain return ...
Author: python
🌐
PythonLessonLab
pythonlessonlab.com › lessons › pathlib-file-paths
Python pathlib: Join Paths, Create Folders, and Read Text — PythonLessonLab
`write_text` can create or replace the file at its path when that file's parent already exists, but it does not create a chain of folders. ... We caught the exception so the demonstration can continue; we should not silently ignore it in a real ...
Published: 2 weeks ago
🌐
Python
bugs.python.org › issue23706
Issue 23706: pathlib.Path.write_text should include a newline argument - Python tracker
March 19, 2015 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/67894
🌐
Real Python
realpython.com › python-pathlib
Python's pathlib Module: Taming the File System – Real Python
1 day ago - Instead of relying on traditional string-based path handling, you can use the Path object, which provides a cross-platform way to read, write, move, and delete files. pathlib also brings together functionality previously spread across other libraries like os, glob, and shutil, making file operations more straightforward. Plus, it includes built-in methods for reading and writing text or binary files, ensuring a clean and Pythonic approach to handling file tasks.
🌐
Python Tutorial
pythontutorial.net › home › python standard library › python path
Python Path: Interact with File System Using Path from pathlib
March 27, 2025 - from pathlib import Path path = Path('notes.md') path.touch()Copy · To write text to a file, you use the write_text() method:
🌐
Python
bugs.python.org › issue20218
Issue 20218: Add methods to `pathlib.Path`: `write_text`, `read_text`, `write_bytes`, `read_bytes` - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/64417
Top answer
1 of 1
2

On the specific case of the file containing the original data or the new data, and nothing in between:

No, it does not do any tricks with opening a temp file in the same directory, populating it, and finishing with an atomic rename to replace the original file. The current implementation is guaranteed to be at least two unique operations:

  1. Opening the file in write mode (which implicitly truncates it), and
  2. Writing out the provided data (which may take multiple system calls depending on the size of the data, OS API limitations, and interference by signals that might interrupt the write part-way and require the remainder to be written in a separate system call)

If nothing else, your code could die after step 1 and before step 2 (a badly timed Ctrl-C or power loss), and the original data would be gone, and no new data would be written.

Old answer in terms of general atomicity:

The question is kinda nonsensical on its face. It doesn't really matter if it's atomic; even if it was atomic, a nanosecond after the write occurs, some other process could open the file, truncate it, rewrite it, move it, etc. Heck, in between write_text opening the file and when it writes the data, some other process could swoop in and move/rename the newly opened file or delete it; the open handle write_text holds would still work when it writes a nanosecond later, but the data would never be seen in a file at the provided path (and might disappear the instant write_text closes it, if some other process swooped in and deleted it).

Beyond that, it can't be atomic even while writing, in any portable sense. Two processes could have the same file open at once, and their writes can interleave (there are locks around the standard handles within a process to prevent this, but no such locks exist to coordinate with an arbitrary other process). Concurrent file I/O is hard; avoid it if at all possible.