14 May 2022

How to read a text file in Python?

https://stackoverflow.com/questions/53919299/python-how-to-properly-use-readline-and-readlines

There are 4 methods.


Method #1 

(Iterate lines by referencing the file pointer)

with open(INFILE, 'r', encoding='utf_8') as f:
    listOfLines = []
    for line in f:    # (Type of 'f' is '_io.TextIOWrapper. 
                      # Yet we can use 'for line in' 
                      # for accessing its lines!)
        listOfLines.append(line.rstrip())  # rstrip() strips off                                               # newline characters

The above method is the best and fastest way, compared with read(), readline(), readlines(), to access a text file. It occupies the least memory at any time. In addition, you need not handle the end-of-file issue as with readline().


Method #2 

(readline())

with open(INFILE, 'r', encoding='utf_8') as f:
    listOfLines = []
    while True:
        if not line:
            break
        line = f.readline()
        listOfLines.append(line.rstrip())


Method #3

(readlines())

with open(INFILE, 'r', encoding='utf_8') as f:
    listOfLines = []
    for line in f.readlines()
        listOfLines.append(line.rstrip())


Method #4

(read())

with open(INFILE, 'r', encoding='utf_8') as f:
    strOfWhole = f.read()

(The END)


No comments:

Post a Comment