How to Read a File in Python: Simple Guide with Examples
To read a file in Python, use the
open() function with the file path and mode 'r' for reading. Then, use methods like read() or readlines() to get the file content, and always close the file or use with to handle it automatically.Syntax
The basic syntax to read a file is:
open('filename', 'r'): Opens the file in read mode.read(): Reads the entire file content as a string.readlines(): Reads the file line by line into a list.close(): Closes the file to free resources.- Using
withautomatically closes the file after reading.
python
file = open('example.txt', 'r') content = file.read() file.close()
Example
This example shows how to open a file, read its full content, and print it. It uses with to handle closing automatically.
python
with open('example.txt', 'r') as file: content = file.read() print(content)
Output
Hello, this is a sample file.
It has multiple lines.
Reading files is easy!
Common Pitfalls
Common mistakes include:
- Not closing the file, which can lock it or waste resources.
- Using the wrong mode (like
'w'which overwrites the file). - Trying to read a file that does not exist, causing an error.
- Reading large files with
read()which can use too much memory.
Always use with to avoid forgetting to close files and handle errors gracefully.
python
try: with open('missing.txt', 'r') as file: content = file.read() except FileNotFoundError: print('File not found, please check the filename.')
Output
File not found, please check the filename.
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Open file | open('file.txt', 'r') | Open file for reading |
| Read all | file.read() | Read entire file content |
| Read lines | file.readlines() | Read file into list of lines |
| Close file | file.close() | Close the file |
| Safe open | with open('file.txt', 'r') as f: | Automatically close file |
Key Takeaways
Use
with open(filename, 'r') to read files safely and automatically close them.Use
read() to get the whole file content as a string or readlines() for a list of lines.Always handle possible errors like missing files with try-except blocks.
Avoid reading very large files all at once to prevent memory issues.
Closing files is important to free system resources.