Read Files
Python · File Handling
Theory
To read a file you open it with open(path, 'r') (r is the default mode), which returns a file object connected to the file on disk. The with statement, with open('sales.csv') as f:, closes the file automatically when the block ends, even if an error happens inside it. If the file does not exist, open() raises FileNotFoundError.
There are several ways to get the content. f.read() returns the whole file as one string; f.readline() returns the next single line; f.readlines() returns a list of all lines, each ending in '\n'; and looping, for line in f:, reads one line at a time, which is the most memory-friendly choice for big files. Add encoding='utf-8' to read text with Hindi names or special symbols reliably, and use line.strip() to remove the trailing newline.
Why we use it
Most real data lives in files - CSV exports, logs, config and text documents. Reading files is how a Python program gets that data in so it can be cleaned, analysed or transformed.
When to use it
Use open() for plain text, logs and custom formats. For tabular data such as CSV or Excel, pd.read_csv() or pd.read_excel() is usually better because it parses columns and types for you.
How it works
- with open('sales.csv') as f:
- Does the file exist? Yes: Get a file object f. No: Raise FileNotFoundError.
- Is the file large? Yes: Loop: for line in f. No: f.read() the whole content.
- Process the text
- Block ends, file closes automatically
Syntax
with open('file.txt', 'r') as f:
data = f.read()Example
with open('sales.csv', 'r') as f:
print(f.read())Key points
- with automatically closes the file afterward, even on error
- read() loads the whole file; readline()/readlines() read incrementally
- for line in f: is the memory-friendly way for large files
- Lines keep their trailing '\n' - use .strip()
- Pass encoding='utf-8' to avoid decoding errors