python


What is File Handling?

File handling is the process of accessing data files stored in the secondary memory of our computer.
It allows us to perform various operations on these files through our program like renaming files, deleting file, moving file and above all reading and writing the contents in a File
Broadly , file handling involves 3 steps:
1. Open the file.
2. Process file i.e perform read or write operation.
3. Close the file.


Opening a file

Before we can perform any operation on a file, we must open it.
Python provides a function called open() to open a file.
Syntax:


fileobject = open(filename, mode)
The filename is the name or path of the file.
The mode is a string which specifies the type operation we want to perform on the file (i.e read, write, append, etc). Default is read


File opening modes

Mode Description
"r" Opens the file for reading. If the file doesn't already exists we will get FileNotFoundError exception​
"w" Opens the file for writing. In this mode, if file specified doesn't exists, it will be created. If the file exists, then it's data is destroyed. If the path is incorrect then we will get FileNotFoundError exception​
"a" Opens the file in append mode. If the file doesn't exists this mode will create the file. If the file already exists then it appends new data to the end of the file rather than destroying data as "w" mode does.
"r+" Opens file for both reading and writing
"w+" Opens a file for both writing and reading. If the file exists then it will overwrite it otherwise it will create it.
"a+" Opens file for appending and reading. If the file already exists then pointer will be set at the end of the file otherwise a new file will be created.

Examples of opening a file

Example 1:​


f = open("employees.txt", "r")​
This statement opens the file employees.txt for reading. ​ ​ Example 2:​

f = open("teams.txt", "w")​
This statement opens the file teams.txt in write mode.​ ​ Example 3:​

f = open("teams.txt", "a")​
This statement opens the file teams.txt in append mode.​
Instead of using relative file paths we can also use absolute file paths. ​
For example:​

f = open("C:/Users/chitranshi/documents/README.txt", "w")​
​ This statements opens the text file README.txt that is in C:\Users\chitranshi\documents\ directory in write mode.​
We can also use something called "raw string" by specifying r character in front of the string as follows:​

f = open(r"C:\Users\sachin\documents\README.txt", "w")​
The r character causes the Python to treat every character in string as literal characters.​
Once we are done working with the file or we want to open the file in some other mode, we should close the file using close() method of the file object as follows:​

f.close()


The textIOWrapper class

The file object returned by open() function is an object of type TextIOWrapper. ​
​ The class TextIOWrapper provides methods and attributes which helps us to read or write data from and to the file. ​
Methods of textIOWrapper Class

Method Description
read([num]) Reads the specified number of characters from the file and returns them as string. If num is omitted then it reads the entire file.
readline() Reads a single line and returns it as a string.
readlines() Reads the content of a file line by line and returns them as a list of strings.
write(str) Writes the string argument to the file and returns the number of characters written to the file.
seek(offset,origin) Moves the file pointer to the given offset from the origin.
tell() Returns the current position of the file pointer.
close() Closes the file.


Exceptions raised in File Handling

Python generates many exceptions when something goes wrong while interacting with files.​
The 2 most common of them are:​
​ FileNotFoundError: Raised when we try to open a file that doesn't exist​
​ OSError: Raise when an operation on file cause system related error.​


Using For Loop to read the file

Python allows us to use for loop also to read the contents of the file line by line.​
​ ​ This is because the object of TextIOWrapper is also a kind of collection/sequence of characters fetched from the file.​
​ ​ The only point is that when we use for loop on the file object , Python reads and returns one line at a time. ​