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())

- tkinter - Hello World! Program
- How to install Python Specific version (3.8, 3.9 or 3.10) using Brew
- How to install SpaCy (NLP Library) on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- How to uninstall pip Python packages
- 3 Ways to find if element is present in a List in Python
- How to Convert Python String to DateTime Object
- Python f-strings Formatted String Literals Syntax and Examples
- Where does brew install python in macOS
- Take input argument from command line in Python Programming
- Advanced print() Function Tutorial and Techniques for Python Developers
- How to add borders to tkinter label text
- Whats new in Python 3.10 Pre-release
- Float built-in function in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- How to check if Key Exists in Python Dictionary?
- Read a file line by line in Python Program
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- What is the Max and Minimum Value of int type in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- Fix: TypeError: can only concatenate str (not int) to str in Python
- How to take user input from the console in a Python program
- [Fix] TypeError: str object is not callable in Python
- 3 Python program to add two numbers
- How to delete a file using Python code example
- Whats new in Python 3.10 Pre-release - Python
- Read file from Windows CMD (Command Line) - Windows
- [Fatal Error] XML The markup in the document following the root element must be well-formed. - Java
- How to highlight the current line in Notepad++ - NotepadPlusPlus
- Android is starting optimizing... app 1 of 1 - Android
- Spring Boot JDBCTemplate Upsert Example (batch insert or update if exists) - Java
- How to add Multiple Rulers in Sublime Text - Sublime-Text
- scp: ssh: connect to host xxxx port 22: Connection refused Error - Linux