Articles → Python → Reading A Text File In Python

Reading A Text File In Python






Example




Picture showing the sample text file with data

Click to Enlarge

myfile = open("test.txt","r")
print(myfile.read())






Picture showing the output of reading the text file in python

Click to Enlarge


Specify The Number Of Characters In Read Function




myfile = open("test.txt","r")
print(myfile.read(10))




Picture showing output of reading the fixed number of characters from the text file

Click to Enlarge


Readline Function




myfile = open("test.txt","r")
print(myfile.readline())




Picture showing the output of Readline function for reading the text file

Click to Enlarge



myfile = open("test.txt","r")
print(myfile.readline(10))  


Picture showing the output of reading the specific number of characters from the text file using the readline function

Click to Enlarge


Read Line By Line




myfile = open("test.txt","r")
for line in myfile:
   print(line)




Picture showing the output of reading the text file line by line

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Monday, March 4, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250