Some examples of reading a file with Python:
Without any additional python packages or modules
with open('test.txt', 'r') as file: lines = file.readlines() print(lines[9]) # Print the 10th line print(lines[0:3]) # Print the first three lineswith open('test.txt', 'r') as file: specified_lines = [0, 7, 11] for pos, line in enumerate(file): if pos in specified_lines: print(line.strip())pip install linecache
import linecache line = linecache.getline('test.txt', 4) print(line) # Print the 4th lineMemory Usage: Using readlines() loads the entire file into memory, which may not be efficient for large files1.with open('test.txt', 'r') as file: specified_lines = [0, 7, 11] for pos, line in enumerate(file): if pos in specified_lines: print(line.strip())
Performance: The linecache module is optimized for reading specific lines and is suitable for large files2.
