File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file:
In addition you can specify if the file should be handled as binary or text mode :
To open a file for reading it is enough to specify the name of the file:f = open("demo_file.txt")
and f = open("demo_file.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.
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:
demo_file.txt
Hello! Welcome to techbaz.org This messege from demo_file.txt and this is testing purposes. |
my_file.py
|
You can a read a file different ways here we discus some basic ways so let's start:
|
By looping through the lines of the file, you can read the whole file, line by line :
|
To write to an existing file, you must add a parameter to the open() function : " a " " w "
my_file.py
|
Note : the " w " method will overwrite the entire file.
To create a new file in Python, use the open() method, with one of the following parameters:
my_file.py
|
Note : Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
To delete a file, you must import the OS module, and run its os.remove() function.
|
To avoid getting an error, you might want to check if the file exist before you try to delete it.
|
It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.