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

(andrew) #1
print(readdata.read())

Line one of a text file
Line two of a text file, just like line one, but
the second one.
Third line of a text file.

When using the open() function, you have to remember
to close the file when you are finished reading from it. If
you don’t, the file will stay open, and you might run in to
file lock issues with the operating system while the
Python app is running. To close the file, you simply use
the close() method on the readdata object:


readdata.close()

Keeping track of the state of the file lock and whether
you opened and closed it can be a bit of a chore. Python
provides another way you can use to more easily work
with files as well as other Python objects. The with
statement (also called a context manager in Python) uses
the open() function but doesn’t require direct
assignment to a variable. It also has better exception
handling and automatically closes the file for you when
you have finished reading in or writing to the file. Here’s
an example:


Click here to view code image


with open("textfile.txt", "r") as data:
print(data.read())

This is much simpler code, and you can use all of the
same methods to interact with the files as before. To
write to a file, you can use the same structure, but in this
case, because you want to append some data to the file,
you need to change how you open the file to allow for
writing. In this example, you can use "a+" to allow

Free download pdf