Sunday, January 28, 2018

Read file in Python

When opening file in python, I think, crucial thing is comprehending '__iter__()' and 'next()' is implemented in TextIOWrapper. Because of that, you can read contents of file as bellow. And that's the standard and best way to read all contents of file line by line.

    
        with open('file name') as f:
            for line in f:
                print(line)
    

Following is the old way to read file in python. Just for memo.
After reading all contents of file, 'readline()' method will return empty string as ''. And boolean value of '' is False. As such EOF can be handled.
    
        with open('file name') as f:
            while True:
                line = f.readline()
                if not line:
                    break
                print(line)
    

No comments:

Post a Comment