Reading the Contents of a File
To read the content of a file we must first open the file in read mode.
The file handle is given to f. We can perform actions on the file using the handle f. ‘r’ specifies that the file is opened in read mode. That filed is optional. If not given, the interpreter assumes the file to be opened in read mode. ‘w’ opens the file in write mode, ‘r+’ in read and write mode, ‘a’ in append mode.
- f.read() : returns the entire file as a string.
- f.readline() : returns line by line as a string.
- f.readlines() : returns a list of strings.
Another way to read a file line by line is:
>>> for line in f:
… print line
- f.seek(5) : goto the 6th byte of the file.
- f.seek(-3,2) : goto the 3rd byte from the last.
- f.seek(2,1) : go forward by 2 byte from the current position.
- f.close() : To close the file and the resources allocated for file operation will be freed up.
Another way of reading is by using with :
>>> with open(‘location’,’mode’) as f: