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('data.txt', 'w') as f:
f.write('Hello World!')
with open('data.txt', 'r') as f:
print(f.read())
2. Copy Files and Folders
import shutil
shutil.copy('src.txt', 'dest.txt') # Copy file
shutil.copytree('src_folder', 'dest_folder') # Copy folder
3. Moving Files and Folders
import shutil
shutil.move('file.txt', 'new_folder/')
4. Compressing Files (ZIP)
import zipfile
with zipfile.ZipFile('example.zip', 'r') as zip:
zip.extractall('folder')
print(zip.namelist())
Benefits: Saves space, faster transfer, archive multiple files.
5. shutil.copy() vs shutil.copytree()
shutil.copy(): Copies single file
shutil.copytree(): Copies entire directory
6. File Deletion
import os
os.remove('file.txt') # Permanent
from send2trash import send2trash
send2trash('file.txt') # 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
logging.basicConfig(level=logging.INFO)
logging.info('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 zipfile.ZipFile('backup.zip', 'w') as zip:
for foldername, subfolders, files in os.walk(folder):
for file in files:
zip.write(...)