File Handling in Python
What happens when you run a program and input some data to be processed. You get result and if you again run your program your previous data are lost. Since Random Access Memory (RAM) is volatile and it frees the memory when the program stops. To solve this problem you can save your data on hard disc in the form of files. Python provides several functions for file handling.
- Open a File
- Read From a File
- Write to a File
- Append to a File
- Closing a File
Open a File
Python provides open() function to open a file which takes two arguments. The first one is file name and another is mode to be a file opened.
We have a file’s screenshot
Read from a File in Python
In Python, read() function is used to read texts or data from a file.
For example a file mytext.txt is written in read mode
Output would be
This text is to be written on file
read() function can have an argument which specifies the number of characters you want to read.
The output would be
readline() specifies number of bytes to be read from a file.
By default it will read all texts from a file.
For example the below code would be
These texts are to be written in file
However, if you specify number of bytes.
Output would be
Write to a File in Python
fw.write(“New texts will override previous texts “)
Screenshot of new mytext.txt file
Append Text to a File in Python
What happens when you open a file in write mode? Your previous written text will be overwritten. However, if you use append mode the text will be written where the privious text ends.
fa.write(“These texts are to be appendend in file”)
Closing a File in Python
It is the best practice is to close a file when you close your program.
close() function is used to close a file in Python
where fr is file object.