In the file I/O in which we perform operation(open,close,read,write,create,deleted etc) on file.
In order to open the file use 'open( )' function.the syntax of opening file is_
variable_name=open("file_name","opening_mode")
with open("file_name","opening_mode") as variable_name: #statements
Here the 'file_name' is the file we want to open.
The given below is the modes of the opening file
modes |
Meaning |
---|---|
r |
file open in read mode and occur error if file is not exists. |
a |
file open in append mode create file if not exists. |
w |
file open in write mode and create file if file is not exists. |
x |
It create a file error occur if the file is already exists. |
t |
Open file in text mode. |
b |
open file in binary mode. |
After opening and perform operation then atlast we close the file using close() function.
variable_name.close()
read() and readline() function are used to read the file .
variable_name.read()
Soppose in file 'eb.py' we have a program to add two number.
file_var=open("eb.py","r") print(file_var.read())
a=10 b=20 print("sum:",a+b)
Soppose in file 'eb.py' we have a program to add two number and we hav to read a fix number of character.
file_var=open("eb.py","r") print(file_var.read(10))
a=10 b=20
It will reads first 10 character including new line,whitespaces etc
readline() reads one lines the file.
variable_name.readline()
Soppose in file 'eb.py' we have a program to add two number.
file_var=open("eb.py","r") print(file_var.readline())
a=10