Python File Handling Tutorial with Example

Python File Handling: Create, Open, Append, Read, Write

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing and reading files.

In this tutorial, we will learn:

  • How to Create a Text File
  • How to Append Data to a File
  • How to Read a File
  • How to Read a File line by line
  • File Modes in Python

How to Create a Text File

With Python you can create a .text files (guru99.txt) by using the code, we have demonstrated here how you can do this

Step 1)

f= open("guru99.txt","w+")
  • We declared the variable f to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
  • Here, we used “w” letter in our argument, which indicates write and will create a file if it does not exist in library
  • Plus sign indicates both read and write.
  • The available option beside “w” are, “r” for read, and “a” for append

Step 2)

for i in range(10):
     f.write("This is line %d\r\n" % (i+1))
  • We have a for loop that runs over a range of 10 numbers.
  • Using the write function to enter data into the file.
  • The output we want to iterate in the file is “this is line number”, which we declare with write function and then percent d (displays integer)
  • So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character

Step 3)

  • This will close the instance of the file guru99.txt stored

Here is the result after code execution

Python FILE Tutorial: Create, Append, Read, Write

When you click on your text file in our case “guru99.txt” it will look something like this

Python FILE Tutorial: Create, Append, Read, Write

How to Append Data to a File

You can also append a new text to the already existing file or the new file.

Step 1)

f=open("guru99.txt", "a+")

Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.

Step 2)

for i in range(2):
     f.write("Appended line %d\r\n" % (i+1))

This will write data into the file in append mode.

Python FILE Tutorial: Create, Append, Read, Write

You can see the output in “guru99.txt” file. The output of the code is that earlier file is appended with new data.

Python FILE Tutorial: Create, Append, Read, Write

How to Read a File

Not only you can create .txt file from Python but you can also call .txt file in a "read mode"®.

Step 1) Open the file in Read mode

f=open("guru99.txt", "r")

Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead

if f.mode == 'r':

Step 3) Use to read file data and store it in variable content


Step 4) print contents

Here is the output

Python FILE Tutorial: Create, Append, Read, Write

How to Read a File line by line

You can also read your .txt file line by line if your data is too big to read. This code will segregate your data in easy to ready mode

Python FILE Tutorial: Create, Append, Read, Write

When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python

Here is the complete code

Python 2 Example

def main():
     f= open("guru99.txt","w+")
     for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
     #Open the file back and read the contents
     #f=open("guru99.txt", "r")
     #   if f.mode == 'r': 
     #     contents
     #     print contents
     #or, readlines reads the individual line into a list
     #fl =f.readlines()
     #for x in fl:
     #print x
if __name__== "__main__":

Python 3 Example

def main():
    f= open("guru99.txt","w+")
    for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
    #Open the file back and read the contents
    #f=open("guru99.txt", "r")
    #if f.mode == 'r':
    #   contents
    #    print (contents)
    #or, readlines reads the individual line into a list
    #fl =f.readlines()
    #for x in fl:
if __name__== "__main__":


  • Python allows you to read, write and delete files
  • Use the function open(“filename”,“w+”) to create a file. The + tells the python interpreter to open file with read and write permissions.
  • To append data to an existing file use the command open(“Filename”, “a”)
  • Use the read function to read the ENTIRE contents of a file
  • Use the readlines function to read the content of the file one by one.

Python File Handling | File Operations in Python | Learn python programming

This Edureka live session on File Handling with Python covers all the important aspects of using files in Python right from the introduction to what fields are, all the way till checking out the major aspects of working with files and using the code-first approach to understand them better.

#python #web-development

What is GEEK

Buddha Community

Python File Handling Tutorial with Example
Ray  Patel

Ray Patel


top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel


Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Art  Lind

Art Lind


How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.


In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

Art  Lind

Art Lind


Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

1. init

class AnyClass:
    def __init__():
        print("Init called on its own")
obj = AnyClass()

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

Init called on its own

2. add

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

class AnyClass:
    def __init__(self, var):
        self.some_var = var
    def __add__(self, other_obj):
        print("Calling the add method")
        return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python