File Handling: Read Mode...
There is a file called read_mode_file.txt
that have the contents of:
read_mode_file.txt
Hi,
My name is: read_mode_file.txt
I am created before the creation of the py file.
Example 1:
The open command will open the py file in the read mode and the for loop will print each line present in the file
import os
# The file "read_mode_file.txt", will be opened with the reading mode
file = open('read_mode_file.txt', 'r')
# Printing each line one by one in the file
for each in file:
print(each)
Example 2:
We will extract a string that contains all characters in the python file then we can use file.read()
file = open("read_mode_file.txt", "r")
print(file.read())
Example 3:
We can read a file using the with
statement
with open("read_mode_file.txt") as file:
data = file.read()
print(data)
Example 4: We can call the certain number of characters from the file
file = open("read_mode_file.txt", "r")
print (file.read(5))
Output of all the examples:
------ File opening in Reading mode ------
--- Example 1 ---
Hi,
My name is: read_mode_file.txt
I am created before the creation of the py file.
--- Example 2 ---
Hi,
My name is: read_mode_file.txt
I am created before the creation of the py file.
--- Example 3 ---
Hi,
My name is: read_mode_file.txt
I am created before the creation of the py file.
--- Example 4 ---
Hi,
M