File Handling


        
        

The key function to do file handling in Python is the open() function. The open() function takes two parameters, the file name and the mode. There are four modes that it accepts:

  • 'r' - read, opens a file for reading, error if the file does not exist
  • 'w' - write, opens a file for writing, create a file if the file does not exist
  • 'a' - append, opens a file for appending, create a file if the file does not exist
  • 'x' - create, create a specified file, error if the file exists

In addition, we can add 't' or 'b' after the mode. The 't' is the text mode, which means that we handle the file as a text. The 'b' is the binary mode, which means we handle the file as a binary file.


Table of Contents

  1. Read
  2. Write
  3. Append
  4. Create

Read

Read mode (r) is used to access a file content into our program. Read in Python requires the read() function (to read the whole file) or a readline() function (to read a single line of text).

Example:

f = open("myfile.txt", 'rt') #open a file print(f.readline()) #reading a single line print(f.read()) #reading a whole file f.close() #close the file

Write

Write mode (w) is a mode that opened a file to write into it. Note that we write to it, not append it. So, when we open an existing document and write into it, the previous content will be deleted and replaced by the new content we just wrote in. To write something, we just need to use write() function.

Example:

f = open("myfile.txt", 'wt') #open a file f.write("Writing some text") #write to the file f.close() #close the file

Append

Append mode (a) is used when we want to write something new in the file without replacing the old content. The append mode uses the same write() function as the write mode.

Example:

f = open("myfile.txt", 'at') #open a file f.write("Adding some text") #append to the file f.close() #close the file

Create

To create a new file in Python, we just need to use the open() function.

Example:

f = open("newfile.txt", 'xt')

Result: a new empty file will be created