Reading a file

Reading a file is achieved using ‘r’ mode. For reading you need to first open the file and then read the content. Once the file completes reading and you have performed the desired operation the file needs to be closed.

We open a file using open() method and assign it to a variable.That variable will hold a file object on which we can call methods like read() and readline() to read the content. Let’s see an example 

f = open('students.txt', 'r')
data = f.read()
print(data)
# close the file 
f.close()

Output

Name  Score
Max   99
Brad  86
Tom   85
Kate  84  

The read() methods also takes optional byte value. If we pass the byte value it read the first byte size item and the if we again call it it reads second byte size item. Lets see an example

f = open("students.txt", "r")
print(f.read(4))  # prints first 4 bytes i.e.: 'Name'
print(f.read(4))  # next four data.i.e nothing

f.close()

Output:

Name
  Sc

Reading a file line by line

We can use readline() method on file object to get line by line data. For example,

f = open("students.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())

f.close()

Output:

Name  Score

Max   99

Brad  86

Looping through file

You can also get line by line item by looping through a file without having to use read() or readline(). For instance,

f = open("students.txt", "r")
for line in f:
    print(line)
f.close()

Output:

Name  Score

Max   99

Brad  86

Tom   85

Kate  84

Leave a Reply

Your email address will not be published. Required fields are marked *