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("filename.txt", "mode")
Example:
f = open("data.txt", "w")
f.write("Hello!")
f.close()
File Handle Attributes:
f.name # filename
f.mode # file mode
f.closed # 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("file.txt", "w")
f.write("Welcome to Python!")
f.close()
writelines():
f = open("file.txt", "w")
f.writelines(["Line 1\n", "Line 2\n"])
f.close()
6. Reading from a File
read(n):
f = open("file.txt", "r")
print(f.read(5))
f.close()
readline():
f = open("file.txt", "r")
print(f.readline())
f.close()
readlines():
f = open("file.txt", "r")
print(f.readlines())
f.close()
Loop reading:
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
7. With Statement
with open("file.txt", "r") as f:
data = f.read()
8. tell() and seek()
tell():
f = open("file.txt", "r")
print(f.tell())
seek(offset, reference):
f.seek(5, 0) # Move to 5th byte
9. Pickle Module
Used to save/load Python objects in binary.
Writing (dump):
import pickle
f = open("data.dat", "wb")
pickle.dump(obj, f)
f.close()
Reading (load):
f = open("data.dat", "rb")
obj = pickle.load(f)
f.close()
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)