Python File Handling - Module 4
1. File Operations in Python
File handling allows us to create, read, write, and close files in Python.
Example - Writing and Reading:
with open('[Link]', 'w') as f:
[Link]('Hello World!')
with open('[Link]', 'r') as f:
print([Link]())
2. Copy Files and Folders
import shutil
[Link]('[Link]', '[Link]') # Copy file
[Link]('src_folder', 'dest_folder') # Copy folder
3. Moving Files and Folders
import shutil
[Link]('[Link]', 'new_folder/')
4. Compressing Files (ZIP)
import zipfile
with [Link]('[Link]', 'r') as zip:
[Link]('folder')
print([Link]())
Benefits: Saves space, faster transfer, archive multiple files.
5. [Link]() vs [Link]()
[Link](): Copies single file
[Link](): Copies entire directory
6. File Deletion
import os
[Link]('[Link]') # Permanent
from send2trash import send2trash
send2trash('[Link]') # Safe delete
7. Assertion and Exceptions
assert a > 0, 'a must be > 0'
if b == 0: raise ZeroDivisionError('b cannot be 0')
8. Logging in Python
import logging
[Link](level=[Link])
[Link]('Start')
Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
9. DivExp Function with Assertion
def DivExp(a, b):
assert a > 0
if b == 0: raise ZeroDivisionError
return a / b
10. Renaming American to European Dates
Use re module to find pattern (MM-DD-YYYY) and rename to (DD-MM-YYYY)
11. Backup Folder into ZIP
def backup_to_zip(folder):
with [Link]('[Link]', 'w') as zip:
for foldername, subfolders, files in [Link](folder):
for file in files:
[Link](...)