Articles → Python → Read text file in python

Read text file in python






Read and Readlines function







Example




Picture showing the sample text file

Click to Enlarge



#Reading the file using read method
myfile = open("c:\\temp\\gyan.txt", "r")
content = myfile.read()
print("Type:", type(content));
print("Content:", content);
myfile.close()

# Read the file line by line
myfile = open("c:\\temp\\gyan.txt", "r")
contentArray = myfile.readlines()
print("Type:", type(contentArray));
print("Content:", contentArray);
myfile.close()




Picture showing the output of reading the text file

Click to Enlarge



with open("c:\\temp\\gyan.txt", "r") as myfile:
    contentArray = myfile.readline()
    print(contentArray);



Posted By  -  Karan Gupta
 
Posted On  -  Monday, June 29, 2020

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250