File Handling in Python - Detailed Notes
1. File Objects
A file object is created using open(). It allows reading, writing or modifying files.
Example: f = open("example.txt", "r")
Modes include 'r', 'w', 'a', 'x', 'b', 't', 'r+' depending on the required operation.
2. File Built-in Functions
Important functions: open(), close(), input(), print().
These allow interaction with files, taking input and printing output.
3. File Built-in Methods
Common methods include:
- read(size), readline(), readlines()
- write(string), writelines(list)
- seek(offset), tell(), flush()
These help in reading/writing and controlling the file pointer.
4. File Built-in Attributes
File attributes include:
- file.name: file name
- file.mode: mode of opening
- file.closed: status of file (open or closed)
5. Standard Files
File Handling in Python - Detailed Notes
Python supports stdin, stdout, stderr via sys module.
stdin: standard input (e.g., keyboard)
stdout: standard output (e.g., screen)
stderr: standard error stream.
6. Command-line Arguments
Arguments passed during script execution are accessed using sys.argv.
Example: python script.py input.txt
Then sys.argv[1] will be 'input.txt'.
7. File System Access
Modules like os and shutil allow directory and file manipulation.
Examples:
- os.mkdir("folder"), os.remove("file.txt")
- os.rename(), os.getcwd(), os.listdir()
8. File Execution
Files can be executed using:
- python filename.py (command-line)
- exec(open("script.py").read()) (within code)
9. Persistent Storage Modules
Modules like pickle, json, shelve help store data permanently.
Example with pickle:
import pickle
File Handling in Python - Detailed Notes
with open("data.pkl", "wb") as f: pickle.dump(data, f)
with open("data.pkl", "rb") as f: data = pickle.load(f)