The process of File Handling refers to how we store the available data or information in a file with the help of a program. Python File Handling refers to the process of working with files. It involves operations such as reading from files, writing to files, appending data etc. The file handling plays an important role when the data needs to be stored permanently into the files.
Python File Open:
Before performing any operation on the file like reading or writing, first we have to open that file. For this we should use python’s inbuilt function open(). At the time of opening, we have to specify the mode which represents the purpose of the opening file.
The open function takes two parameters: filename and mode.
F=open(filename,mode)
The mode determines how the file is opened and how we can interact with its contents. For example, if we want to read data from a file, we need to open the file in “read” mode. If we want to write data to a file, we need to open the file in “write” mode. If we want to append data to an existing file, we need to open the file in “append” mode. Choosing the wrong file mode can cause errors or unexpected behavior in the program. For example, if we try to write to a file that is opened in “read” mode, we will get an error.
Mode | Description | File Pointer Position | Creates File if Not Exists | Truncates Existing File |
r | Read-only | Beginning of the file | No | No |
r+ | Read and write (updating) | Beginning of the file | No | No |
w | Write-only (overwrite or create) | Beginning of the file | Yes | Yes |
w+ | Write and read (overwrite or create) | Beginning of the file | Yes | Yes |
a | Append-only (append or create) | End of the file | Yes | No |
a+ | Append and read (append or create) | End of the file | Yes | No |
r mode:
r mode opens an existing file for read operation, shows error if the file does not exist. The r
mode opens the file for reading only. The file pointer is placed at the beginning of the file. If the file does not exist, open()
raises a FileNotFoundError
.
Example-1
file=open(‘abc.txt’,’r’)
for x in file:
print(x)
Example-2
file=open(‘abc.txt’,’r’)
print(file.read())
Example-3
file=open(‘abc.txt’, ‘r’)
print(file.readline())
print(file.readline())
Example-4
with open(‘abc.txt’) as file:
data=file.read()
print(data)
w mode:
w mode opens an existing file for write operation. If the file already contains some data, then it will be overwritten but if the file is not present then it creates the file as well. The w
mode opens the file for only writing. We cannot read in this mode. The file pointer is placed at the start of the file. If the file exists, its content is truncated. If the file does not exist, it is created. Be careful to avoid any data loss.
Example
file=open(‘hi.txt’,’w’)
file.write(“Hello Students”)
file.write(“\nWelcome to the Institute”)
file.write(“\nLearn Computer science”)
file.close()
a mode:
a mode opens an existing file for append operation. Append mode add data to an existing file. It won’t overwrite existing data. If a file does not exist, append mode creates the file.
The “a”
mode opens the file for appending data. The file pointer is placed at the end of the file, so new content is added after the existing content. If the file does not exist, it is created.
Note: The key difference between a
and w
is that w
truncates the existing content of the file, while a
appends data to the end of the file without modifying the existing content.
Example:
file=open(‘abc.txt’,’a’)
file.write(“\nWelcome to India”)
file.write(“\nWelcome to Assam”)
file.write(“\nWelcome to Tinsukia”)
file.close()
r+ mode
r+ mode read and write data into a file. This mode does not overwrite the existing data, but we can modify the data. The r+ mode opens the file for both reading and writing. Like r, If the file does not exist, open() raises a FileNotFoundError.
Example
file=open(“hi.txt”, “r+”)
data= file.read()
print(data)
file.write(“Assam is a beautiful place”)
w+ mode
The w+
mode opens the file for both writing and reading. Like w
, it too will overwrite the previous file if the file exists, or create a new one if it doesn’t.
Example
f=open(“tsk.txt”, “w+”)
f.write(“Beautiful Assam”)
f.write(“\nBrahmaputra”)
f.seek(0)
data= f.read()
print(data)
a+ mode
The a+
mode opens the file for both appending and reading. The file pointer is placed at the end of the file, so new content is added after the existing content. If the file does not exist, it is created.
Example:
f=open(“tsk.txt”, “a+”)
f.write(“\nKaziranga National park”)
f.seek(0)
data= f.read()
print(data)
File Handling Function:
Function | Description |
open() | Used to open a file |
read() | Used to read whole content of file at a time |
readline() | Used to read a single line from the file. |
write() | Used to write a string to the file. |
writelines() | Used to write multiple strings at a time. |
close() | Used to close the file. |
tell() | Returns the current position of the file pointer(cursor) within the file. |
seek() | Used to change or move the position of file pointer while reading or writing a file. |
writelines():
writelines() method is used to write multiple strings at a time.
Example:
file=open(‘hello.txt’,w)
file.writelines(‘This is the firstline\n’ ‘This is the second line\n’ ‘This is the third line’)
file.close()
tell() :
tell method returns the current position of the file pointer(cursor) within the file.
Example
file= open(‘hi.txt’, ‘r’)
data=file.read(10)
print(data)
position=file.tell()
print(“Current position:”, position)
file.close()
seek() :
The seek() method is used to change or move the position of file pointer while reading or writing a file. The position (index) of the first character in files is zero, just like the string index.
Example:
file= open(“hi.txt”, “r”)
file.seek(10) #move to 11 character
print(file.read()) #read from 10th character