Python File Handling Tutorial

In general a file is a named location to store information. In python there are various file related operations that we can perform. In this context, first we have to open a file. Python has a built-in open() function to open a file. This function returns a file object, also called a handle. At the time of opening a file, we can specify a mode like read, write, append or create.


There are four different modes to open a file:

  • "r" - Read - 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 - Creates the specified file, returns an error if the file exists
  • 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)

#Open a file and perform read operation
f1 = open("e:\demo.txt", "r")
print(f1.read())

Python is a programming language. Python is developed by Guido Van Rossum.


f2 = open("e:\demo.txt", "r")
for k in f2:
 print(k)

Python is a programming language. Python is developed by Guido Van Rossum.


#Display first 16 characters
f3 = open("e:\demo.txt", "r")
print(f3.read(16))

Python is a prog


f3 = open("e:\demo.txt", "r")
print(f3.readline())

Python is a programming language. Python is developed by Guido Van Rossum.


f1 = open("e:\demo.txt", "r")
print(f1.readline())
f1.close()

Python is a programming language. Python is developed by Guido Van Rossum.


#write and append operation
f4=open("e:\demo.txt","w")
f4.write("Python is widely popular programming language.")
f4.close()

f4=open("e:\demo.txt","a")
f4.write("Python came to the market in 1991.")
f4.close()

f5=open("e:\demo1.txt","x")


#delete a file
import os
os.remove("e:\demo2.txt")

#delete folder
import os
os.rmdir("e:\myfolder")

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext