iptracker
answered Aug 17 '21 00:00
simple two step to read file in Python :
1. open file with open() method , open() method return file object
fp=open("path of the file")
open(file path) take file path as argument .
as you see above we store the open() method return object to another variable for later use.
alternatively open(filename, mode) , the open method has a second argument as "r" - read mode or 'w' - write mode
fp=open("path of the file","r")
we need here read mode so we passed 'r' as the second argument. if not pass anything as a second argument then it takes default as 'r' - read mode for the file open method.
2. read the opened file with read() method , read() method invoked by file object
data=fp.read()
read() method return full file data.
alternatively readline() method return one line per method call
3. after completion of the read file, close the file object
fp.close()
close() method release the file object
Python code to read a file :
fp=open("readfile.py")
data=fp.read()
fp.close()