Home » Python

Python File readlines() Method with Example

Python File readlines() Method: Here, we are going to learn about the readlines() method, how to get all lines from the file in Python?
Submitted by IncludeHelp, on December 22, 2019

File readlines() Method

readlines() method is an inbuilt method in Python, it is used to get all lines from the file, the method is called with this object (current file stream/IO object) and returns all available lines in the file, we can also specify the total number of bytes to read from the line.




  • len – It is an optional parameter and it can be used to specify the total number of bytes to read from the file. It's default value is -1 that specifies all lines. If the len is greater than the total number of bytes of the file, then no more content will return.

Return value:

The return type of this method is <class 'list'>, it returns the lines in the form of a list.


# Python File readlines() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# writing content in the file
myfile1.write("Shivang, 21, Indore\n")
myfile1.write("Pankaj, 27, Mumbai\n")
myfile1.write("Rambha, 16, Indraloka\n")
myfile1.write("Urvarshi, 18, Indraloka\n")
myfile1.write("Menaka, 17, Indraloka\n")

# closing the file

# reading the file (opening file in 'r' mode)
myfile1 = open("hello1.txt","r")

# reading and printing the file's content  
# using readlines()
print("file's content (using readlines() method)...")

# reading a total number of bytes
# seeking file's position to 0th position
# reads only 10 bytes

# reads next 300 bytes, if no more bytes
# method will not read more bytes

# closing the file


file's content (using readlines() method)...
['Shivang, 21, Indore\n', 'Pankaj, 27, Mumbai\n', 'Rambha, 16,Indraloka\n', 'Urvarshi, 18, Indraloka\n', 'Menaka, 17, Indraloka\n']
['Shivang, 21, Indore\n']
['Pankaj, 27, Mumbai\n', 'Rambha, 16, Indraloka\n', 'Urvarshi,18, Indraloka\n', 'Menaka, 17, Indraloka\n']

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.