read(), readline(), readlines() & xreadlines() func in Python

While doing a regression analysis, I had to read & parse through a large .dat file. I called readline() func but was surprised to see that I was actually iterating through every single character in the first line!

with open(filePath, 'r') as f:
    for line in f.readline():
        print line

Then realization dawned upon me!

* read(size) >> size is an optional numeric argument and this func returns a quantity of data equal to size. If size if omitted, then it reads the entire file and returns it

* readline() >> reads a single line from file with newline at the end

* readlines() >> returns a list containing all the lines in the file

* xreadlines() >> Returns a generator to loop over every single line in the file

2 Responses to read(), readline(), readlines() & xreadlines() func in Python

  1.  

    Very nice. Thanks for explanation. Can you please give examples?

  2.  

    how can we read asd binaryfile into ascii file???

leave your comment