Basics of File Handling in Python

File handling in Python Programming language



File handling is an important part of any web application. The web applications can create, read, update, and delete with the help of programming languages. Python is the best programming language which has several functions for creating, reading, updating and deleting files. We can read, append, write and create using Python programming language. Let us understand the basics of file handling in Python programming language.

Open function


The open() function has two parameters namely filename and mode. The modes can be either “r”, “a”, “w” or “x”.

"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

 



Not only this we can specify whether the file is text or binary by using “t” or “b”


"t" - Text - Default value. Text mode

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

To open the text file named testfile.txt use the command

F=open(demo”testfile.txt”)

Here the command is same as

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

In case the file is stored on specific location then we have to specify the location as well.


f = open("D:\\myfiles\hello.txt", "rt")

Reading only parts of the files in Python


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

How to create files in python


There is a difference between append and write parameters in Python programming language. x is used to create the file if the the name of the file doesnot exist in the directory.

f = open("myfile.txt", "x")

This will return error if the file exist.
How to create files in python if the file doesnot exist

f = open("myfile.txt", "w")

How to delete the file in Python




To remove the files or delete the files in Python we need to import the OS files in Python and use remove function. The systax is show as given bellow

import os
os.remove("demofile.txt")

The example imports the os files and uses remove function of the os files to delete demofile.txt.

We can also use logic to find if the file exists and then delete the file


import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")


The file handling in Python is extensively used by python developers or python programmer for developing dynamic fully responsive website, Python application development and Python software application development.

 

Post a Comment

0 Comments