In file I/O, we perform operations (open, close, read, write, create, delete, etc.) on a file.
Open FileTo open a file, use the `open()` function. The syntax for opening a file is:
Syntax 1variable_name = open("file_name", "opening_mode")Syntax 2
with open("file_name", "opening_mode") as variable_name: # statements
Here, the `file_name` refers to the file you want to open.
Modes of Opening FileThe table below shows the modes for opening a file:
Modes |
Meaning |
---|---|
r |
Opens a file in read mode. Error occurs if the file does not exist. |
a |
Opens a file in append mode. Creates the file if it does not exist. |
w |
Opens a file in write mode. Creates the file if it does not exist. |
x |
Creates a new file. Error occurs if the file already exists. |
t |
Opens a file in text mode. |
b |
Opens a file in binary mode. |
After performing operations, close the file using the close() function.
Syntaxvariable_name.close()Read File
read() and readline() functions are used to read a file.
Syntax of read() Functionvariable_name.read()Example 1
Suppose the file `eb.py` contains a program to add two numbers:
file_var = open("eb.py", "r") print(file_var.read())Output
a = 10 b = 20 print("sum:", a + b)Example 2
Suppose the file `eb.py` contains a program, and you want to read a fixed number of characters:
file_var = open("eb.py", "r") print(file_var.read(10))Output
a = 10 b = 20
It reads the first 10 characters, including newlines and whitespaces.
readline() reads one line of the file at a time.
Syntax of readline() Functionvariable_name.readline()Example 1
Suppose the file `eb.py` contains a program to add two numbers:
file_var = open("eb.py", "r") print(file_var.readline())Output
a = 10