
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read Multiple Lines from a File Using Python Readlines
In Python, the file.readlines() method is a convenient way to read multiple lines from a file into a list. Each line from the file becomes an element in the list.
It reads all the lines from a file and stores them in a list, which can be easily manipulated in your code.
Basic Usage of file.readlines() Function
The simplest way to use a file.readlines() is by opening a file, calling the method, and printing the results.
Example
The following example code reads all lines from sample.txt into a list and prints each line without extra whitespace.
# Open the file in read mode with open('sample.txt', 'r') as file: lines = file.readlines() # Print the lines for line in lines: print(line.strip())
Following is the output for the above code.
Hello, World! Welcome to Python programming. Have a great day!
Reading Lines with a Condition
You can also read lines from a file and filter them based on a specific condition, such as checking for a keyword.
Example
The following code reads the file and prints only the lines that contain the word "Python", removing any extra spaces.
# Open the file and filter lines that contain the word "Python" with open('sample.txt', 'r') as file: lines = file.readlines() # Print lines that contain the word "Python" for line in lines: if "Python" in line: print(line.strip())
Following is the output for the above code.
Welcome to Python programming.
Stripping Whitespace and Processing Lines
In this method, we will read the lines and also strip any leading or trailing whitespace, allowing for cleaner data.
Example
In this example, the code reads the lines from the file, strips whitespace from each line, and prints the cleaned lines.
# Open the file and process lines to remove whitespace with open('sample.txt', 'r') as file: lines = file.readlines() # Strip whitespace and print each processed line cleaned_lines = [line.strip() for line in lines] for line in cleaned_lines: print(line)
Following is the output for the above code.
Hello, World! Welcome to Python programming. Have a great day!