Python Docs
Python File Reading — Full Cheat Sheet
What is File Handling?
Python uses the open() function to handle files. It returns a file object that allows reading, writing, or modifying files.
open() Syntax
open(filename, mode)Common File Modes
- r – Read (default)
- a – Append
- w – Write
- x – Create
- t – Text mode (default)
- b – Binary mode
Basic File Reading
Reads the entire file content.
f = open("demofile.txt", "r")
print(f.read())Reading From a File Path
f = open("D:\\myfiles\\welcome.txt")
print(f.read())Using the with Statement
with automatically closes the file after use. It is the recommended way to work with files.
with open("demofile.txt") as f:
print(f.read())Closing Files
If you don't use with, always call close().
f = open("demofile.txt")
print(f.readline())
f.close()Reading Only Part of the File
Specify the number of characters inside read(n).
with open("demofile.txt") as f:
print(f.read(5)) # Reads 5 charactersReading Lines
Read One Line
with open("demofile.txt") as f:
print(f.readline())Read Two Lines
with open("demofile.txt") as f:
print(f.readline())
print(f.readline())Loop Through File Line-by-Line
with open("demofile.txt") as f:
for line in f:
print(line)Summary
- open() creates a file object
- read() reads entire file or first n characters
- readline() reads one line
- loop to read file line-by-line
- with auto-closes file
- close() closes manually when not using with