Hey people… in this tutorial we are discussing about file handling in python.
Introduction:
File handling in python is the process of reading and writing data to and from a file stored in a computer system. The built in open() function is used to open a file and perform operations on it. The first argument to the open() function is the mode, which specifies the type of operation that needs to be performed on the file.
Once the file is opened, you can perform the operations like reading the content of the file using the read() method, writing data to the file using the write() method, moving the file pointer to the specific location using the seek() method and getting the current position of the file pointer using the tell() method.
File handling in python is an essential aspect of programming that enables us to store multiple data in a permanent and organized manner.
opening of file
The open() function consists of following modes
“r”: this opens the file for reading only. It is the default mode.
“w”: this opens the file for writing only. It will create the file if it does not exist, and it will overwrite the file if it exists.
“a”: this opens the file for appending. This mode will create the file if it does not exist.
“x”: this opens the file for exclusive creation. It will give an error if the file already exists in the system.
“b”: this opens the file in binary mode.
“t”: this opens the file in text mode. It is the default mode.
syntax:
f=open(filename, mode)
example:
f=open("demofile.txt", "rt")
Read Mode:
In python, you can write to a file using the write() method. This method takes a string as its argument and writes it to the file. If you want to write multiple lunes of text to the file ,you can use write lines() method.
syntax:
f=open("filename","w")
Append mode;
Append mode is used to add the information to the existing file.
syntax:
f=open("filename", "a")
Create mode:
Create mode also known as exclusive create. Creates the file if it does not exist.
syntax:
f=open("filename", "x")
Reading files in python:
After importing a file into an object, Python offers numerous methods to read the contents.
syntax:
f=open("file.txt") print(f. read(), end="")
Read parts of the file:
1)Read Lines:
To read lines and iterate through a files contents, use a for loop:
f = open("file.txt") for line in f: print(line, end="")
2)Close Files:
A file remains open until invoking the close() function.
f. close()
3)delete files:
we import the os library and delete a file withe the following:
import os os. remove("file.txt")