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.
For examples
-
- 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
f=open(“mytext.txt”)
Where f is the file object, by default in Python, open file mode is read.
You can specify read mode
f=open(“mytext.txt”, “r”)
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
>>>fr=open(“mytext.txt”, “r”)
>>>print(fr.read())
Output would be
This text is to be written on file
>>>fr=open(“mytext.txt”, “r”)
read() function can have an argument which specifies the number of characters you want to read.
For example
>>>fr=open(“mytext.txt”, “r”)
>>>print(fr.read(9))
The output would be
This text
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
>>>fr=open(“mytext.txt”, “r”)
>>>print(fr.readline())
These texts are to be written in file
However, if you specify number of bytes.
For example
>>>fr=open(“mytext.txt”, “r”)
>>>print(fr.readline(9))
Output would be
This text
Write to a File in Python
fw=open(“mytext.txt”, “w+”)
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=open(“mytext.txt”, “a”)
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.
>fr=open(“mytext.txt”, “r”)
>>>print(fr.read())close() function is used to close a file in Python
>>>fr.close()
where fr is file object.