Lesson 1 of 0
In Progress

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:

  1. r: open an existing file for a read operation.
  2. w: open an existing file for a write operation. If the file already contains some data then it will be overridden.
  3. a:  open an existing file for append operation. It won’t override existing data.
  4.  r+:  To read and write data into the file. The previous data in the file will be overridden.
  5. w+: To write and read data. It will override existing data.
  6. a+: To append and read data from the file. It won’t override existing data.

Example

file_1 = open(“backup.txt”)
file_2 = open(“backup.txt”, “r”)

The Read() Function

The open() function returns a file object, which has a read() method for reading the content of the file.

Example

file = open(“backup.txt”, “r”)
print(file.read())

By looping through the lines of the file, you can read the whole file, line by line:

Example

file = open(“backup.txt”, “r”)
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. 

file = open(“backup.txt”, “r”)
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:

  1. a:  open an existing file for append operation. It won’t override existing data.
  2. 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 = open(“backup.txt”, “a”)
file.write(“Add new lines to the backup file!”)
file.close()

Open the file backup.txt and overwrite the content.

file = open(“backup.txt”, “w”)
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

import os
os.remove(“backup.txt”)