Read a File Line-by-Line in Python

Reading a file line by line in Python entails opening the file, and then using a loop or an iterator to iterate through each line of the file. Here's how you can achieve this with examples:

Using a Loop

file_name = "sample.txt" # Open the file in read mode with open(file_name, "r") as file: # Read and process each line for line in file: print(line.strip()) # strip() removes newline characters

read line by line

Using an Iterator

file_name = "sample.txt" # Open the file in read mode with open(file_name, "r") as file: lines = file.readlines() # Read all lines into a list # Process the lines for line in lines: print(line.strip())

Both methods allow you to read and process each line of the file individually. The "with" statement ensures proper file closure, and the strip() method removes newline characters for cleaner output.

Conclusion

When working with large files, using a loop or an iterator is more memory-efficient, as it doesn't load the entire file content into memory at once.