Python - File Handling

File handling is use to store the data in a file instead of just displaying it. Python has several functions for creating, reading, writing, updating, and deleting files.

File Handling - open()

The open() function is used to open the file. The open() function takes two parameters; filename, and mode.

f = open("anyfilename.txt")

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"x" - Create - Create a file, returns an error if the file exist

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
f = open("anyfilename.txt","rt")
f = open("anyfilename.txt", "x")

File methods:

  1. open() - open the file
  2. close() - close the file. It is a good practice to always close the file when you are done with it.
  3. read() - reading the content of the file
  4. read(5) - read only 5 characters
  5. readline() - return one line
  6. write() - write contents in a file
  7. remove() - remove the file

Example 1: Open the file and read its content

f = open("myfile.txt", "r")
print(f.read())
f.close()

If the file is located in a different location, you will have to specify the file path:

f = open("D:\\myfolder\\myfile.txt", "r")
print(f.read())
f.close()

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

f = open("myfile.txt", "r")
print(f.read(5))
f.close()

Example 2: return one line by using the readline() method

f = open("myfile.txt", "r")
print(f.readline())
f.close()

By calling readline() two times, you can read the first 2 lines:

f = open("myfile.txt", "r")
print(f.readline())
print(f.readline())
f.close()

Read the whole file, line by line using for loop:

f = open("myfile.txt", "r")
for x in f:
    print(x)
f.close()

File Handling - Write

Write() function is use to write the content in a file, if file doesnot exists it create it, if file exits, it remove its contents and write it (overwrite the contents)

Example : Write contents in a file

f = open("myfile.txt", "w")
f.write("Write text using python write() function")
f.close()

Example : Write contents in a file and read it

f = open("myfile.txt", "w")
f.write("Write text using python write() function")
f.close()

f = open("myfile.txt", "r")
print(f.read())
f.close()

Example : Append contents in a file and read it

f = open("myfile.txt", "a")
f.write("Add more contents using write function with append mode")
f.close()

f = open("myfile.txt", "r")
print(f.read())
f.close()

File Handling - Delete file

You can also delete a file using Python remove() function. To delete a file, you must import the OS module.

import os
os.remove("myfile.txt")
import os
try:
    os.remove("myfile.txt")
    print("file deleted")
except:
    print("file not found")

File Handling - Check if File exist

To avoid getting an error, you might want to check if the file exists before you try to delete it:

import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

File Handling - Delete Folder

To delete an entire folder, use the os.rmdir() method. You can only remove empty folders.

import os
os.rmdir("myfolder")