Monday, October 3, 2016

[ Exceptions & Files ] Reading Files

file = open("filename.txt","r")
cont = file.read()
print(cont)
file.close

The contents of a file that has been opened in text mode can be read using read method.
This will print all of the contents of the file "filename.txt"


To read only a certain amount of file => you can provide a number as an argument to the read function , This determines the number of bytes that should be read.

You can male more calls to read on the same file object to read more of the file byte by byte .
With no argument , read turns the rest of the file.


After all contents in a file have been read , any attempts to read further from that file will return an empty string.

To retrieve each line in a file , you can use the readlines method to return a list in which each element is a line in the file.

file = open("filename.txt","r")
print(file.readlines())
file.close()


file = open("filename.txt","r")

for line in file:
    print(line)

file.close

No comments:

Post a Comment