File I/O

In the file I/O in which we perform operation(open,close,read,write,create,deleted etc) on file.

Open File

In order to open the file use 'open( )' function.the syntax of opening file is_

Syntax 1

variable_name=open("file_name","opening_mode")
Syntax 2
with open("file_name","opening_mode") as variable_name:
   #statements

Here the 'file_name' is the file we want to open.

Modes of opening file

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.

Close file

After opening and perform operation then atlast we close the file using close() function.

Syntax
variable_name.close()

Read File

read() and readline() function are used to read the file .

Syntax of read() function

variable_name.read()

Example 1

Soppose in file 'eb.py' we have a program to add two number.

file_var=open("eb.py","r")
print(file_var.read()) 
Output
a=10
b=20
print("sum:",a+b)
Example 2

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)) 
Output
a=10
b=20

It will reads first 10 character including new line,whitespaces etc

readline() reads one lines the file.

Syntax of readline() function

variable_name.readline()

Example 1

Soppose in file 'eb.py' we have a program to add two number.

file_var=open("eb.py","r")
print(file_var.readline()) 
Output
a=10