File Handling in Python - Notes with Examples
1. What is a File?
A file is a named location on secondary storage where data is stored permanently for later use.
2. File Handle (or File Object)
When a file is opened using open(), Python returns a file handle (file object).
Syntax: file_handle = open("[Link]", "mode")
Example:
f = open("[Link]", "w")
[Link]("Hello!")
[Link]()
File Handle Attributes:
[Link] # filename
[Link] # file mode
[Link] # True if closed
3. Types of Files
- Text File: Human-readable (.txt, .csv)
- Binary File: Byte format (.jpg, .dat, .exe)
4. File Modes
Mode | Purpose
---------------------------
'r' | Read
'w' | Write (overwrite)
'a' | Append
'r+' | Read + Write
'w+' | Write + Read
'a+' | Append + Read
Add 'b' for binary: 'rb', 'wb'
5. Writing to a File
write():
f = open("[Link]", "w")
[Link]("Welcome to Python!")
[Link]()
writelines():
f = open("[Link]", "w")
[Link](["Line 1\n", "Line 2\n"])
[Link]()
6. Reading from a File
read(n):
f = open("[Link]", "r")
print([Link](5))
[Link]()
readline():
f = open("[Link]", "r")
print([Link]())
[Link]()
readlines():
f = open("[Link]", "r")
print([Link]())
[Link]()
Loop reading:
with open("[Link]", "r") as f:
for line in f:
print([Link]())
7. With Statement
with open("[Link]", "r") as f:
data = [Link]()
8. tell() and seek()
tell():
f = open("[Link]", "r")
print([Link]())
seek(offset, reference):
[Link](5, 0) # Move to 5th byte
9. Pickle Module
Used to save/load Python objects in binary.
Writing (dump):
import pickle
f = open("[Link]", "wb")
[Link](obj, f)
[Link]()
Reading (load):
f = open("[Link]", "rb")
obj = [Link](f)
[Link]()
10. Summary Table
Function Description
--------------------------------------
write() Writes a string
writelines() Writes multiple strings
read(n) Reads n characters
readline() Reads one line
readlines() Reads all lines as list
tell() Returns cursor position
seek() Moves cursor
dump() Saves object (binary)
load() Loads object (binary)