Reading Entire File :
The read( ) method reads the entire content of the file. Reading limited characters is also possible by mentioning the number of characters inside the parentheses.
Python
file = open("data.txt", "r") content = file.read() print(content) file.close() #output Hello Python Welcome to file handling Python
file = open("data.txt", "r") print(file.read(5)) file.close() #output Hello Reading One Line :
The readline( ) method reads one line at a time.
Python
file = open("data.txt", "r") line1 = file.readline() line2 = file.readline() print(line1) print(line2) file.close() Reading All Lines :
The readlines( ) method returns all lines as a list.
Python
file = open("data.txt", "r") lines = file.readlines() print(lines) file.close() #output ['Hello Python\n', 'Welcome to file handling\n'] Using with Statement :
Python
with open("data.txt", "r") as file: content = file.read() print(content)