DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

convention), with a newline character at the end (\n for
Python). There are just two functions that you need to
know when working with a text file: open() and
close().


To open a file and read in its contents, you have to first
tell Python the name of the file you want to work with.
You do this by using the open() function and assigning
the output to a Python object (the variable readdata in
this case). The function returns a file handle, which
Python uses to perform various operations on the file.
The code looks as follows:


Click here to view code image


readdata = open("textfile.txt", "r")

The open() function requires two arguments: the name
of the file as a string and the mode that you want to open
the file. In the preceding example, it opens the file in
read mode. There are numerous options you can use
when you set mode, and you can combine them in some
cases to fine-tune how you want Python to handle the
file. The following are some of the options:


r: Open for reading (default)
w: Open for writing, truncating the file first
x: Open for exclusive creation, failing if the file already exists
a: Open for writing, appending to the end of the file if it exists
b: Open in binary mode
t: Open in text mode (default)
+: Open for updating (reading and writing)

With the previous code, you now have a file handling
object named readdata, and you can use methods to
interact with the file methods. To print the contents of
the file, you can use the following:


Click here to view code image

Free download pdf