Read Text File in Python

Read Text File in Python programming by using fopen() os library function to read any text file by using mode 'r' to read text file.

Program Reading Text File

Program

fo = open("C://MyTxtFile.txt", "r+") #opening file
str = fo.read() #reading file.
print("Read String is:") #and printing.
print(str) #and printing.
fo.close() #Close opened file.
Output
Read String is:
The is line 1 text in MyTxtFile file
The is line 2 text in MyTxtFile file

Program Reading Text File Text

Program

fobj = open("C://MyTxtFile.txt")
print(fobj.read()) #reading and printing.
Output
The is line 1 text in MyTxtFile file
The is line 2 text in MyTxtFile file

Program Reading and Printing a Line of Text File

Program

fobj = open("C://MyTxtFile.txt")
print(fobj.readline(2)) #reading 2 number Line and printing.
Output
Th

Program Reading and Printing Text of Text File using Loop
Program

fobj = open("C://MyTxtFile.txt")
for x in fobj: #loop looping on file Text.
    print(x, end="") #and printing.
Output
The is line 1 text in MyTxtFile file
The is line 2 text in MyTxtFile file

Read Text File Text from Specific Line Number to Specific Line Number
Program

fromLine = 0
toLine = 13
def index_exists(c, ln):
    return (0 <= ln < len(c)) or (-len(c) <= ln < 0)
with open("C://MyTxtFile.txt") as f:
    content = f.readlines()
content = [x.strip() for x in content]
counter = 0
for lnumber in content:
    counter = counter + 1
if toLine > counter:
    toLine = counter
for lineNumber in range(fromLine, toLine):
    if index_exists(content, lineNumber):
        print(content[lineNumber])
if(toLine == counter):
    print("All lines are read")
Output
The is line 1 text in MyTxtFile file
The is line 2 text in MyTxtFile file
All lines are read