Python - Read Files
Assume we have the following file, located in the same folder as Python:
freedomfile.py
WELCOME TO FREEDOM TUTORIALS
FREEDOM TUTORIALS IS THE BEST TUTORIALS AMONG THE BEST ONES.
IT LENDS INFORMATION ABOUT ALL THE COURSES BETTER ENOUGH.
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content of the file:
f = open("freedomfile.py", "r")
print(f.read())
======o/p=======
WELCOME TO FREEDOM TUTORIALS
FREEDOM TUTORIALS IS THE BEST TUTORIALS AMONG THE BEST ONES.
IT LENDS INFORMATION ABOUT ALL THE COURSES BETTER ENOUGH.
By default the read() method returns the whole text, but you can also specify how many characters you want to return:
Return the 5 first characters of the file:
f = open("freedomfile.py", "r")
print(f.read(15))
========o/p========
WELCOME TO FREE
We can return one line by using the readline() method.
Read one line of the file :
f = open("freedomfile.py", "r")
print(f.readline())
========o/p========
WELCOME TO FREEDOMTUTORIALS
By calling readline() two times, you can read the two first lines:
Read two lines of the file:
f = open("freedomfile", "r")
print(f.readline())
print(f.readline())
========o/p=======
WELCOME TO FREEDOMTUTORIALS
FREEDOMTUTORIALS IS THE BEST TUTORIALS AMONG THE BEST ONES.
It is a good always to close the file when we are done with it.
f = open("freedomfile.py", "r")
print(f.readline())
f.close()
========o/p=========
WELCOME TO FREEDOMTUTORIALS
Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.