Loading, reading, and writing files with base Python
When we talk about "base" Python, we are talking about built-in components of the Python software. We already saw one of these components with the math
module in Chapter 2, Getting Started with Python. Here, we'll first cover using the built-in open()
function and the methods of file objects to read and write basic text files.
Opening a file and reading its contents
We will sometimes find ourselves wanting to read a plain text file, or maybe another type of text file, such as an HTML file. We can do this with the built-in open
function:
file = open(file='textfile.txt', mode='r')
text = file.readlines()
print(text)
In the preceding example, we first open a file called textfile.txt
in "read" mode. The file
argument provides the path to the file. We have given a "relative" path in the preceding snippet, meaning it looks for textfile.txt
in the current directory...