File Handling in Python
File Handling in Python
Python uses file access modes to control how a file is opened and manipulated. Here's a summary:
Mode | Description
------|-------------
'r' | Read: Opens file for reading. File must exist.
'w' | Write: Creates new file or truncates existing.
'a' | Append: Adds data at end of file. Creates file if it doesn't exist.
'x' | Exclusive creation: Creates new file. Fails if file exists.
'b' | Binary mode: For non-text files like images or audio.
't' | Text mode: Default; used for reading/writing text.
'r+' | Read + Write: File must exist.
'w+' | Write + Read: Overwrites existing or creates new.
'a+' | Append + Read: Allows reading and appending.
Examples:
f.read(5)
print("Position after 5 chars:", f.tell())
Python Program:
filename = "numbers.txt"