Python File Handling Made Simple

Python File Handling Made Simple

Working with Files in Python - Open, Read, Write, Close and Manage Files Effortlessly

In my previous blog, you learned the basics of Python. So now let's dive deep into file handling in Python.

So file handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.


1) Python Open Files

The key function used for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode. There are four different methods for opening a file in Python:

  • "r" - Read - Default value. Opens a file for reading, error if the file does not exist

  • "a" - Append - Opens a file for appending, creates the file if it does not exist

  • "w" - Write - Opens a file for writing, 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 also specify if the file should be handled in binary or text mode:

  • "t" - Text - Default value. Text mode

  • "b" - Binary - Binary mode (e.g. images)

1.1) Syntax for opening

To open a file for reading it is enough to specify the name of the file:

f = open("test.txt")

The code above is the same as:

f = open("test.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.


2) Python Read Files

Assume we have the following file, located in the same folder as Python:

Hello! Welcome to test.txt
This file is for testing purposes.
Have a Nice Day!

So, to open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file.

Example:

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

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

#Open a file on a different location:
f = open("D:\\Vineet\\CS\\Python\\test.txt", "r")
print(f.read())vineet

2.1) Read Only Parts of the File

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

#Return the 5 first characters of the file:
f = open("test.txt", "r")
print(f.read(5))

2.2) Read Lines

You can return one line by using the readline() method:

#Read one line of the file:
f = open("test.txt", "r")
print(f.readline())
#Read two lines of the file:
f = open("test.txt", "r")
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file, line by line:

#Loop through the file line by line:
f = open("test.txt", "r")
for x in f:
  print(x)

Note: You should always close your files, in some cases, changes made to a file may not show until you close the file.


3) Python Write/Create File

So, to write to an existing file, you must add a parameter to the open() function:

  • "a" - Append - will append to the end of the file

  • "w" - Write - will overwrite any existing content

#Open the file and append content to the file:
f = open("test.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("test.txt", "r")
print(f.read())
#Open the file and overwrite the content:
f = open("test.txt", "w")
f.write("Old Content is now deleted!!")
f.close()

#Open and read the file after the overwriting:
f = open("test.txt", "r")
print(f.read())

Note: The "w" method will overwrite the entire file.

3.1) Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

  • "x" - Create - will create a file, returns an error if the file exists

  • "a" - Append - will create a file if the specified file does not exist

  • "w" - Write - will create a file if the specified file does not exist

#Create a file called "test2.txt":
f = open("test2.txt", "x") #Empty File is created
#Create a new file if it does not exist:
f = open("myfile.txt", "w")

4) Python Delete File

To delete a file, you must import the OS module, and run its os.remove() function:

#Remove the file
import os
os.remove("test2.txt")

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

#Check if file exists, then delete it:
import os
if os.path.exists("test2.txt"):
  os.remove("test2.txt")
else:
  print("The file does not exist!!")

To delete an entire folder, use the os.rmdir() method:

#Remove the folder "CS":
import os
os.rmdir("CS")

Note: You can only remove empty folders.


The concepts discussed in this blog should help you make your own files and add functionality to the same.

This will be very handy when you are trying to create an application by making the process easy. Now, you should also be able to use these file operations to develop applications easily with the help of Python.

Until then take care, Happy Learning!

Thanks for Reading!