File Handling in Python

0 Comments

Apart from database or cloud we need to have other mechanism to store our data and to overcome this issue Files is a good option. File play an important part as we can store our data in it. 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.

This tutorial is about python file operations which we can use to save and retrieve our data.

Python has functions like create, read, update, delete which we can used and apply to store our data.

A file operation takes place in the following order:

-> Open a file
-> Read or write (perform operation)
-> Close the file

Below are some file modes

“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

“t” – Text – Default value. Text mode

“b” – Binary – Binary mode (e.g. images)

“+”  –   Opens a file for updating (reading and writing)

Syntax

open(filename, mode) #open a file

read(filename, mode) #read a file

write(datatoinput) #write in a file

os.remove(“abc.txt”) #delete a file

close() #close a file


Leave a Reply

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