π Day 84/150 – File Read Operation in Python
Reading files is one of the most common tasks in Python. Whether you're working with text files, logs, configuration files, or datasets, Python provides simple and efficient ways to read file contents. In this post, we'll explore four different methods to perform file read operations.
Method 1 – Read the Entire File
The simplest way to read a file is by using the read() method. It loads the complete content of the file into a single string.
file = open("sample.txt", "r") content = file.read() print(content) file.close()
Output
Hello World
Welcome to Python
Best for: Small text files where reading the entire content at once is acceptable.
Method 2 – Read File Using with Statement
Using the with statement is the recommended approach because it automatically closes the file after reading.
with open("sample.txt", "r") as file: for line in file: print(line.strip())
Output
Hello World
Welcome to Python
Best for: Most real-world Python programs.
Method 3 – Read File Line by Line
Instead of loading the whole file into memory, you can iterate through each line.
with open("sample.txt", "r") as file: for line in file: print(line.strip())
Output
Hello World
Welcome to Python
Best for: Large files where memory efficiency matters.
Method 4 – Read All Lines into a List
The readlines() method stores every line as a separate element in a list.
['Hello World\n', 'Welcome to Python\n']with open("sample.txt", "r") as file: lines = file.readlines() print(lines)
Output
Best for: When you need to process individual lines later.
Which Method Should You Use?
- read() – Reads the complete file as one string.
- with open() – Safest and most recommended way to work with files.
- Line-by-line iteration – Ideal for reading large files efficiently.
- readlines() – Useful when each line needs to be stored separately.
Key Takeaways
- Use with open() whenever possible because it automatically closes the file.
- read() is simple but should be used only for smaller files.
- Reading files line by line is more memory-efficient for large files.
- readlines() returns a list where each element represents one line.
- File handling is an essential Python skill used in automation, data analysis, logging, and many real-world applications.


0 Comments:
Post a Comment