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.
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.
fobj = open("C://MyTxtFile.txt")
print(fobj.read()) #reading and printing.
fobj = open("C://MyTxtFile.txt")
print(fobj.readline(2)) #reading 2 number Line and printing.
fobj = open("C://MyTxtFile.txt")
for x in fobj: #loop looping on file Text.
print(x, end="") #and printing.
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")