Lesson #16: Files
Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.
Before performing any operation on the file like reading or writing, first, we have to open that file.
The Open() Function
The open()
function takes two parameters; filename, and mode.
There are many different methods (modes) for opening a file:
- r: open an existing file for a read operation.
- w: open an existing file for a write operation. If the file already contains some data then it will be overridden.
- a: open an existing file for append operation. It won’t override existing data.
- r+: To read and write data into the file. The previous data in the file will be overridden.
- w+: To write and read data. It will override existing data.
- a+: To append and read data from the file. It won’t override existing data.
Example
The Read() Function
The open()
 function returns a file object, which has a read()
 method for reading the content of the file.
Example
print(file.read())
By looping through the lines of the file, you can read the whole file, line by line:
Example
for x in file:
print(x)
The Close() Function
The close()
command terminates all the resources in use and frees the system of this particular program.Â
print(file.read())
file.close()
The Append And Write Mode
If you want to write to an existing file, you must add a parameter to the open()
 function:
- a:  open an existing file for append operation. It won’t override existing data.
- w:Â open an existing file for a write operation. If the file already contains some data then it will be overridden.
Example
Open the file backup.txt
and append content to the file.
file.write(“Add new lines to the backup file!”)
file.close()
Open the file backup.txt
and overwrite the content.
file.write(“The content has been overwriten!”)
file.close()
Delete a File
In order to delete a file in Python, you need to import the OS
module, and run the function os.remove()
.
Example
os.remove(“backup.txt”)