Guide Of Python File Handling

In this tutorial, we going to learn file handling with Python. At the end of the article, you will be ready to work with any file in Python.

Understanding Files

KhanAcademy File Image

Files are named locations on a disk to store related information. They are used to store data on the local hard disk (permanent storage).

When you use a variable, your data is written to RAM (Random Access Memory), so it is saved while your program is running, then deleted.

That’s why we write permanent data, that is, the data that should be kept even if the computer is turned off, to the hard disk.

In this article, we will learn how to retrieve, edit and delete data stored on the hard disk with python.

1 – Open File in Python

We have a built-in function to open files: open(). This function returns a file object. Open has 2 parameters: the file name and the mod name.

We can open the files in different modes depending on what we are going to do at that moment. For example; edit mode, read mode, etc.

# Read only mode (default)
f = open("name.txt")

# Write Mode
f = open("name.txt" , "w")

# Append Mode
f = open("name.txt" , "a")

# Rading and Writing Mode
f = open("name.txt" , "+")

All of the above modes work in text mode by default, but we have another mode other than text mode, it is the binary mode.

Before passing the binary code, we can set the encoding mode with the encoding parameter, the encoding value may change in operating systems, it is good to specify to avoid this.

# Set Text Mode Encoding
f = open("test.txt","r",
         encoding = "utf-8")

For example, you will have files that need to be opened in binary mode: files such as images, gifs, and mp3 are examples.

Binary mode is a special mode used to open non-text-based files, and it does not come by default, so it is not specified.

# Open Image (Binary Mode)
f = open("test.jpg","rb")

2 – Creating File in Python

This mode is mostly used to create a new file in write mode. For example, you will request to write to a file that does not exist before.

In X mode you will get an error if the file exists, otherwise, it will create the file and start it in write mode.

Even if X mode only starts the file in write mode, it can be run in both writing and read mode by adding + next to it.

# Create new file 
# Mode: Just Write
f = open("new.txt" , "x")

# Create new file 
# Mode: Write and Read
f = open("new.txt" , "x+")

# Close file

If there is no file in the system, a file with the name we give will be created and in writable mode.

However, it is dangerous to use the X mode in this way. If the program is restarted, it will give an error, let’s fix it.

def createNewFile(name):
  f = open("{}.txt".format(name) , "x")
  print("File Exists")

This function basically creates a file according to the given name, if the file exists in the system, an exception is returned, if not, the file is created and the file is closed.

Using the final statement here allows you to get an error. For example, if the “try” is not performed, the variable named “f” is not recognized and you will get an error.

3 – Read Content on File

In this section, we will look at how we can store and print the data in the files we open.

For this, we can use the read() function provided by the file object, this function returns the values in the file.

# Open file and read 
f = open("text.txt" , "r")
content =

# Close file

We are going to look again the close function, but now just knowing that you closed the file is enough.

Firstly, we opened the file in reading mode after that, we stored data of text.txt in the content variable and we closed the file when we don’t need it anymore.

We can specify how much data we will get, for example, if you want the 4 char, simply set the first parameter of the function to 4.

# Open file and read first 4 element
f = open("text.txt" , "r")
content =

# Close file

Reading Rows of Files

We can use for loop with the aim of reading each row step by step. Let’s read a file that contains names.

# Open and read file
f = open("nameFile.txt" , "r")
content =

# seperate the lines
lines = content.split("\n")

# write lines
for i in content:
  print("Name:" , i)

Of course, we can filter the data we store. For example, the code below allows us to filter only names that start with the initial letter a.

import re

# open file and read line
f = open("example.txt", "r")
content =

# filter just started with "a"
def filter_letter(line):
    if re.match('^a', line):
        return True
        return False

# seperate the lines
lines = content.split("\n")

# Write just started with a
for i in lines:

If you start the for loop without separating the texts with the split function, you can examine each letter one by one.

For example, if you return the content of the variable content, each element will receive 1 letter.

# Open file and read 
f = open("example.txt", "r")
content =

# Get all letter on content
for i in content:

4 – Writing on Files with Python

You can write new content on your file and append new lines to your file. It’s very simple in python so let’s see how to do this.

We have 2 modes for editing files these are: writing mode (w), append mode (a) It is important not to confuse these modes as they can cause data loss.

1 – Writing Mode (w)

w mode is a dangerous mode, if you open your file with this mode and write data, the old written data will be deleted.

The reason for this is that the writing mode, unlike the append mode, was created to enter data into a file from scratch, so you do not add data, you write the data from 0.

# Open file in write mode
f = open("example.txt", "w")

# Write 2 sentence
f.write("Test Sentence 1\n")
f.write("Test Sentence 2")

# Close file

2 sentences will be written in the content of the file named test.txt, but if the program is run for the second time, 2 more sentences are not written, they are reset and the same sentences are rewritten.

2 – Append Mode (a)

When you want to overwrite your old data, you can use append mode, unlike write mode, it keeps the old data.

# When it's started file content removed
f = open("example.txt", "w")
f.write("Line 1\n")

# It appends line 2 (data is stored)
f = open("example.txt", "a")
f.write("Line 2")

When you start the program for the first time, the content of the file is completely reset, then line 1 is written.

Then we close the file, but since we open it with append mode, the data is not deleted. After that, Line 2 is written and the file is closed again.

5 – Close File in Python (3 different way)

When we’re done with the files, we need to close them properly so we don’t waste our resources.

Python has a garbage collector to remove unreferenced objects, but we shouldn’t rely on it to close the files.

  • The garbage collector can increase RAM usage when more file processing is required.
  • In Python, changes to your file are applied when the file is closed, and if the file takes a while to close, the changes cannot be viewed during that time.

For reasons like this, it’s usually better to use the close function instead of the garbage collector. Now let’s learn how to close the file in different ways.

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


We closed files like this previous part but it’s not safe cause if the program terminates when before close file functions, the file is not closed.

So how can I close the program more safely? The answer is simple: use the power of try-except-else.

   f = open("test.txt", "r")
   print("Error: File not open")

This way we guarantee that the file is closed properly even if an exception is thrown that causes the program flow to stop.

Of course, it can be difficult to write try-finally for each file separately, so you can write more readable code using “with” the keyword.

with open("test.txt","r") as f:
  # Code Block

You don’t need to call the close function again using with, it’s automatically taken care of in itself.

Some Imporant File Functions

In this part, we going to look at some important functions for file handling in Python. These functions can increase your productivity.

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

# clears the internal buffer

# Checks the readability

# Read 1 line (stores current line)

# Get current file location

# Checks the writable

Some functions can be life-saving, these are the most used commands in daily projects. You can find more in the documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *