< previous | Table of Contents | next > |
7.3 OPENING FILES
As mentioned, we can use the built-in open()
function to open files and return a file object, allowing us to access and manipulate the file's contents.
Let's try to open a simple .txt
file which contains some lines of text on our desktop with the following contents.
The syntax for the open()
function is as follows.
The only parameter that’s mandatory
is the path to the file, in the example as /Users/enriquesarap/Desktop/file_open_example.txt
. This can be a string or an object that represents the path.
Mode
is not mandatory, and the default for the mode parameter is r
, which means reading from the file. This allows you to read the contents of the file.
The third argument, encoding
, is also optional; the default encoding in Python 3 is UTF-8. An encoding is a system that maps characters to bytes. The most common encoding today is UTF-8, which can represent every character in the Unicode standard.
We also use the built-in .read()
method to read the entire file. We will provide more detail about this method and others in the next section of this chapter.
FILE MODES
r
is the default mode and allows you to read the file's contents.w
allows you to overwrite the contents of the file. If the file does not exist, it will be created. Also, very important to note that opening a file in write mode will immediately delete all the existing content, so be careful.a
stands for appending and allows data to be written at the end of the file. If the file does not exist, it is created.r+
means that the file is open for reading and writing. The file will be opened from the beginning. It will also overwrite the existing contents of the file.w+
means that the file is open for both writing and reading. Similarly,w
overwrites the existing file or creates a new one if the file does not exist.a+
opens the file for both appending and reading. Data written to the file is added at the end. If a file does not exist, it will be created. It will not overwrite existing data.
KEY THINGS TO REMEMBER
open()
andclose()
methods allow us to open files, return a file object for reading and writing, and then, importantly, close them.- File path is the only mandatory parameter that needs to be specified. By default the file mode parameter is
r
and UTF-8 in Python for encoding. - File modes include
r
for reading,w
for writing,a
for appending. Note thatw
will overwrite the entire existing file and create a new file if the file does not exist. - UTF-8 is the encoding that should be preferred and is the default in Python.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |