Writing Text to a File
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.
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.
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.
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.
.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.
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.
Become a Member to join the conversation.