Writing Text to a File
00:00 In this lesson, you’ll get a hands-on introduction to reading and writing text files in Python, so go ahead and jump into IDLE. First, you’re going to need some sample text to work with.
00:12
You can obtain this text by importing the standard-library module called this
. As you can see, it prints out the so-called Zen of Python, which is a humorous poem expressing the principles of the language.
00:26
You can grab that and assign it to a variable. Let’s call the variable text
. You need the triple-quote to start a multiline string. Otherwise, you’ll get a SyntaxError
.
00:40
The text contains some newline characters noted with \n
.
00:46 Now, there are several ways in which you can write this text to a file. First of all, you need to open the file in write-only mode, remembering to specify the character encoding.
01:05
In real-life projects, you should generally prefer using the pathlib
module to open a file in Python because you’ll get improved portability. However, calling the built-in open()
function here in IDLE will be more convenient for the sake of explaining things. Even though the Zen of Python is an English text, you should make it a habit to use UTF-8 whenever possible, which is the best way to ensure that your text will be easily read and understood by any computer or text editor.
01:34
The letter code w
opens the file in write-only mode, which means that Python will create the file for you or erase its contents if the file already exists. So remember to be careful with this mode.
01:47
Also, when you open the file in the write-only mode by setting the mode
argument to the letter code w
, then you won’t be able to call any of the reading methods on the associated file object. As soon as you call file.read()
, you’re getting an UnsupportedOperation
error, which means that method doesn’t work in files opened in the write-only mode.
02:09
One of the operations that is supported in this mode, though, is the .write()
method. You can call this method with a string as an argument to write a whole text in one go.
02:25
The value returned by .write()
is the number of characters written to the file. In this case, it’s exactly the same as the length of your text.
02:36
Note that in binary mode, the .write()
method returns the number of actual bytes written to the file instead of the number of characters, which might be slightly different.
02:46
Calling .write()
with the entire text is only suitable for reasonably short texts that can fit in your computer’s memory. If your text is longer or isn’t known up front, then you can write the text file incrementally by calling the .write()
method multiple times in your with
code block. Here’s an example.
03:04
Let’s open another file called incremental.txt
, also in .write()
mode and with the UTF-8 encoding.
03:17
You can keep calling .write()
more than once with a different arguments until you leave the with
code block.
03:32
This time, the first call to .write()
returns seven characters and the second one six characters. You can confirm the contents of the file you’ve just created by reading it back using Python. Now that you know how to write text into a file, it’s time to implement code that will retrieve the text from that file.

Bartosz Zaczyński RP Team on Aug. 25, 2024
@ajackson54 Are you trying to open a folder instead of a file by any chance? Can you check if the specified path is correct? Also, your user might have insufficient permissions to read a file from the specified path, or the file could be owned by another user. Unfortunately, this error message doesn’t provide much detail on its own, so you might need to check the file permissions or try running your script with elevated privileges.
ajackson54 on Aug. 26, 2024
I checked the correctness of the specified path. I decided to import pathlib and then set a variable home to Path.home(). Then I put the home variable as a parent to zen.txt in the open function. It works now. Thank you Bartosz.
Lilian Cipciriuc on Feb. 10, 2025
Minute 2.19
Error (that doesn’t correspond to the one in the lecture)
>>> text = """\
... The Zen of Python, by Tim Peters
...
... Beautiful is better than ugly.
... Explicit is better than implicit.
... Simple is better than complex.
... Complex is better than complicated.
... Flat is better than nested.
... Sparse is better than dense.
... Readability counts.
... Special cases aren't special enough to break the rules.
... Although practicality beats purity.
... Errors should never pass silently.
... Unless explicitly silenced.
... In the face of ambiguity, refuse the temptation to guess.
... There should be one-- and preferably only one --obvious way to do it.
... Although that way may not be obvious at first unless you're Dutch.
... Now is better than never.
... Although never is often better than *right* now.
... If the implementation is hard to explain, it's a bad idea.
... If the implementation is easy to explain, it may be a good idea.
... Namespaces are one honking great idea -- let's do more of those!"""
>>> with open(zen.txt, mode = 'w', encoding = 'utf-8') as file
File "<python-input-2>", line 1
with open(zen.txt, mode = 'w', encoding = 'utf-8') as file
^
SyntaxError: expected ':'
>>> with open(zen.txt, mode = 'w', encoding = 'utf-8') as file:
... file.read()
...
Traceback (most recent call last):
File "<python-input-5>", line 1, in <module>
with open(zen.txt, mode = 'w', encoding = 'utf-8') as file:
^^^
NameError: name 'zen' is not defined. Did you mean: 'len'?
Phil on Feb. 10, 2025
Hi @Lilian Cipciriuc 👋🏻
You’ve forgotten to enclose the filename inside a pair of double-quotes:
with open("zen.txt", mode="w", encoding="utf-8") as file:
file.write(text)
Hope that helps 😀

Bartosz Zaczyński RP Team on Feb. 10, 2025
@Lilian Cipciriuc On the first highlighted line after declaring the file
variable, you forgot to include a trailing colon (:
), which starts a new block of code. You fixed that on the second highlighted line, but then there was another problem—you forgot to enclose the filename (zen.txt
) in quotation marks ("
). This is the expected code:
with open("zen.txt", mode = "w", encoding="utf-8") as file:
file.write()
Become a Member to join the conversation.
ajackson54 on Aug. 25, 2024
Hello, Bartosz. I’m getting an ‘[Errno 13] permission denied’ error with both the zen.txt and the incremental.txt. I’ve tried it twice and received the same result.