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.

Syntax:

    file_object.readlines(len)

Parameter(s):

  • 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.

Example:

# 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
myfile1.close()

# 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)...")
print("myfile1.readlines()...")
print(myfile1.readlines())

# reading a total number of bytes
# seeking file's position to 0th position
myfile1.seek(0)
# reads only 10 bytes
print("myfile1.readlines(10)...")
print(myfile1.readlines(10))

# reads next 300 bytes, if no more bytes
# method will not read more bytes
print("myfile1.readlines(300)...")
print(myfile1.readlines(300))

# closing the file
myfile1.close()

Output

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.