Let's write to a text file.
Here we're using the
open function on a text file called
my_file.txt (using a
with block to automatically close the file when we're done working with it) and we're calling the
write method on the file object we get back to write text to that file:
>>> with open("my_file.txt") as f: ... f.write("This is text!") ... f.write("And some more text") ...
When we run this code, we'll see an error:
>>> with open("my_file.txt") as f: ... f.write("This is text!") ... f.write("And some more text") ... Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'
We get an error because Python's
open function accepts more than just a filename:
>>> help(open) Help on built-in function open in module io: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd =True, opener=None)
open function also accepts a
mode, and by default that mode is
r (for read mode).
In order to write text to this file, we need to specify write mode.
Here we can see the modes accepted by
========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= ===============================================================
The default mode is
r, in fact more explicitly it's
rt, for read text mode.
We need to specify the mode as
w or (even more explicitly)
wt for write text mode (we want text mode as opposed to binary mode).
We're going to specify a mode (
wt) as we open up our file:
>>> with open("my_file.txt", mode="wt") as f: ... f.write("This is text!") ... f.write("And some more text")
Notice that we're not passing our mode in as positional argument, even though we could:
>>> with open("my_file.txt", "wt") as f:
mode as a named argument to be explicit.
When we open this file now and call its
write method, we'll get back the number of characters that were written to this file:
>>> with open("my_file.txt", mode="wt") as f: ... f.write("This is text!") ... f.write("And some more text") ... 13 18
If we take a look at the file contents of
my_file.txt now, we'll see that our text was written to the file:
This is text!And some more text
But it wasn't written exactly how we wanted! We wanted to write two separate lines to this file, but instead, Python wrote just one line.
Python wrote just one line because it wrote exactly the text we gave to it, and we didn't give it any newline characters (
\n) to write.
To write two separate lines to this file, we should end each of our lines in a newline character:
>>> with open("my_file.txt", mode="wt") as f: ... f.write("This is text!\n") ... f.write("And some more text\n")
Now as expected, we have two separate lines in this file:
This is text! And some more text
Let's open a file without using a
>>> f = open("my_file.txt", mode="wt")
And then call the
write method on the our file object to write some text to this file:
>>> f.write("some text") 9
Has our file been written to at this point? What's your guess? 🤔
The answer is, probably not! Our file is empty right now:
Python doesn't write to a file until the file is flushed or closed:
>>> f.flush() >>> f.close()
The best way to make sure that everything will be written to your file as soon as you're done working to it is to use a
with block to use your file as a context manager.
This will make sure your file is closed automatically as soon as you're done working with it.
To write to a text file in Python, you can use the built-in
open function, specifying a mode of
You can then use the
write method on the file object you get back to write to that file.
It's best to use a
with block when you're opening a file to write to it.
Hello friendly web visitor! 👋
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing. In the case of Python that means writing Python code. If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well. You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.