File Handling — Python basics

Ramahanishagunda
4 min readJan 4, 2021

--

Hello guys, let's learn how to handle files in python.

Why do we need file handling?

Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and to perform various operations on it.

Types of files

There are many types of files in our os. Below are few files which we mostly use.

What you may know as a file is slightly different in python. In python we have two files text file and binary file, i.e if the file is not in text format it will be in binary format.

What is File Handling?

File handling is an important part of any web applications. The operations in file handling are CRUD operations.

where C = creating , R= reading, U = updating, D = deleting.

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

The process of handling the files is creating file and then opening the file, working upon the file and then closing the file.

Now, lets look at the syntax of open function in this filename can be any name that you want and mode indicates different modes for opening a file. Lets check the operations.

“r” — Read — Opens a file for reading, error if the file if it 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.

Reading text file in python can be done using file.read(). If we want first five characters in a file then we can write file.read(5). There are many functions some of them are given below.

We can also do looping over a file object which makes it fast and efficient.

Writing 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.

Note: The “w” method will overwrite the entire file.

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

“x” — Create ,

“a” — append,

.“w” — write.

syntax ==> file=open(“file name” , “x’) or file=open(“file name” , “w”).

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

Before deleting we have to check whether the file exists or not using os.path.exists(file name).

If you want to delete a folder you need to use os.rmdir(folder name).

Summary

In this blog you will know how to open , read, write , delete the files with examples.

Thats all for this blog, Thanks for reading.

--

--