Locked lesson.
About this lesson
Exercise files
Download this lesson’s related exercise files.
Opening and Closing Files.docx59.3 KB Opening and Closing Files - Solution.docx
59.1 KB
Quick reference
Opening and Closing Files
In this video we'll learn how to open and close files.
When to use
Use this whenever you need to open or close an external file with Python.
Instructions
To open a file, create a file object:
my_file = open("names.txt", "r")
# the first parameter is the name of the file, the second parameter is the open mode (r, w, a, +, b)
The open file modes (how you will open a file) are as follows:
r = Read only, pointer at beginning of file
w = Write only, overwrites the entire file
a = Appending, pointer at the end of the file
b = Binary, opens binary files
+ = Both reading and writing, pointer at beginning of file
To find the name of an open file:
print(my_file.name)
To find out if a file has been closed:
print(my_file.closed)
To find out the mode of an opened file:
print(my_file.mode)
To close a file:
my_file.close()
Hints & tips
- my_file = open("names.txt", "r") # Open a file
- my_file.close() # Close a file
Lesson notes are only available for subscribers.