Reading a file and processing it line by line is the most memory-efficient way, especially when the file is too huge, in the four below Python programs we will see how to read a file line by line,
Example 1:file_name = "sample-file.txt";
with open(file_name) as sample_file:
line = sample_file.readline()
while line:
line = sample_file.readline()
print(line.strip())
Example 2:
file_name = "sample-json-file.txt";
with open(file_name) as myFile:
for line in myFile:
print(line.rstrip())
Example 3:
If memory is not a concern, you can read the whole file in memory and store it as a list,
# Reading file line-by-line in
# memory at once
file_name = "sample-json-file.txt";
with open(file_name) as myFile:
lines = myFile.readlines()
for line in lines:
print(line.rstrip())
Example 4: using tuple()
lines = tuple(open("sample-json-file.txt", 'r'))
for line in lines:
print(line.rstrip())

Content of file - Python Example
More Posts related to Python,
- Comments in Python Programming
- tkinter - Hello World! Program
- How to install Python 3.11 on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- Change label (text) color in tkinter
- Python Hello World! Program with code example (snippet)
- Calculate discount amount python code
- Take input argument from command line in Python Programming
- How to pip install Python Modules in VSCode
- Tkinter - add x and y padding to label text
- Python raise error with message example
- Check if String Contains a Substring - Python
- Python Program To Calculate Simple Interest (SimpleInterest.py)
- What does b prefix before a String mean in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to List all Packages installed using pip [Python]
- Convert Float to String in Python
- Change the background of Tkinter label or text
- How to Install Python Modules in VS Code
- Indent Python code in Notepad++
- Validate email address in Python using regular expression (regex)
- Python: Fix command not found pip or pip3 on zsh shell
- TypeError: must be str, not int [Fix Python]
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python - Convert float to String
More Posts:
- Delete a Directory using Mac Terminal Command - MacOS
- MySQL 1005 Error : SQLSTATE: HY000 (ER_CANT_CREATE_TABLE) Message: Can't create table '%s' (errno: 150) - MySQL
- JSON Datatypes : Tutorial - Json-Tutorial
- Open Current Working Directory in Finder using Mac Terminal - MacOS
- How to subscribe nest aware? - Google
- Internet Explorer browser auto redirect to Microsoft Edge for compatibility with modern web sites - Microsoft
- Flash Player will no longer be supported after December 2020. Turn off [Google Chrome] - Chrome
- How to find AUTO_INCREMENT Fields value in MySQL table - MySQL