Advanced Python Concepts: File Handling and Exception Handling
- File Handling
File Handling dalam Python memungkinkan kita untuk membaca dari dan menulis ke file di sistem. Ini sangat penting untuk berbagai operasi seperti menyimpan data, membaca konfigurasi, dan memproses log.
Konsep Dasar:
- open(): Membuka file
- read(), readline(), readlines(): Membaca dari file
- write(), writelines(): Menulis ke file
- close(): Menutup file
- with statement: Mengelola konteks file (membuka dan menutup secara otomatis)
Common modes:
'r'
- read'w'
- write (truncates the file if it exists)'a'
- append'r+'
- read and write
Contoh dasar:
a) Opening a file:
pythonfile = open('example.txt', 'r') # 'r' for read mode
b) Reading from a file:
pythoncontent = file.read() # Read entire file line = file.readline() # Read a single line lines = file.readlines() # Read all lines into a list
c) Writing to a file:
pythonfile = open('example.txt', 'w') # 'w' for write mode file.write('Hello, World!')
d) Appending to a file:
pythonfile = open('example.txt', 'a') # 'a' for append mode file.write('New content')
e) Managing file metadata:
pythonimport os file_size = os.path.getsize('example.txt') last_modified = os.path.getmtime('example.txt')
python# Membaca file with open('data.txt', 'r') as file: content = file.read() # Menulis ke file with open('output.txt', 'w') as file: file.write('Hello, World!')
Practical Implementations in Various Industries:
- Banking and Fintech:
- Transaction Logging: Record all financial transactions in a log file for auditing purposes.
- Customer Data Management: Store and retrieve customer information from files.
Example:
pythondef log_transaction(transaction): with open('transactions.log', 'a') as file: file.write(f"{transaction.timestamp},{transaction.account_id},{transaction.amount}\n") def get_customer_data(customer_id): with open('customers.csv', 'r') as file: for line in file: if line.startswith(customer_id): return line.strip().split(',') return None
- E-commerce:
- Product Catalog Management: Store product information in CSV or JSON files.
- Order Processing: Write order details to files for record-keeping.
Example:
pythonimport json def update_product_catalog(product): with open('products.json', 'r+') as file: catalog = json.load(file) catalog[product['id']] = product file.seek(0) json.dump(catalog, file, indent=2) file.truncate() def process_order(order): with open('orders.log', 'a') as file: file.write(json.dumps(order) + '\n')
- Healthcare:
- Patient Records: Store and retrieve patient medical histories from files.
- Appointment Scheduling: Manage appointment schedules using file-based storage.
Example:
pythondef update_patient_record(patient_id, new_data): filename = f"patient_{patient_id}.json" with open(filename, 'r+') as file: record = json.load(file) record.update(new_data) file.seek(0) json.dump(record, file, indent=2) file.truncate() def get_appointments(date): with open('appointments.csv', 'r') as file: return [line.strip().split(',') for line in file if line.startswith(date)]
- Production and Inventory Management:
- Inventory Tracking: Maintain inventory levels in files.
- Production Logs: Record production data in log files.
Example:
pythondef update_inventory(product_id, quantity_change): with open('inventory.csv', 'r+') as file: lines = file.readlines() for i, line in enumerate(lines): if line.startswith(product_id): current_quantity = int(line.strip().split(',')[1]) new_quantity = current_quantity + quantity_change lines[i] = f"{product_id},{new_quantity}\n" break file.seek(0) file.writelines(lines) file.truncate() def log_production(product_id, quantity): with open('production.log', 'a') as file: file.write(f"{datetime.now()},{product_id},{quantity}\n")
- Logistics:
- Shipment Tracking: Store and update shipment statuses in files.
- Route Planning: Read route information from configuration files.
Example:
pythondef update_shipment_status(shipment_id, status): with open('shipments.csv', 'r+') as file: lines = file.readlines() for i, line in enumerate(lines): if line.startswith(shipment_id): lines[i] = f"{shipment_id},{status},{datetime.now()}\n" break file.seek(0) file.writelines(lines) file.truncate() def get_route_plan(route_id): with open('routes.json', 'r') as file: routes = json.load(file) return routes.get(route_id)
- Maintenance:
- Equipment Logs: Record maintenance activities in log files.
- Scheduled Maintenance: Read maintenance schedules from files.
Example:
pythondef log_maintenance(equipment_id, activity): with open('maintenance.log', 'a') as file: file.write(f"{datetime.now()},{equipment_id},{activity}\n") def get_maintenance_schedule(): with open('maintenance_schedule.csv', 'r') as file: return [line.strip().split(',') for line in file]
- Project Management:
- Task Tracking: Store project tasks and their statuses in files.
- Project Reports: Generate reports by reading project data from files.
Example:
pythondef update_task_status(project_id, task_id, status): filename = f"project_{project_id}.json" with open(filename, 'r+') as file: project_data = json.load(file) for task in project_data['tasks']: if task['id'] == task_id: task['status'] = status break file.seek(0) json.dump(project_data, file, indent=2) file.truncate() def generate_project_report(project_id): filename = f"project_{project_id}.json" with open(filename, 'r') as file: project_data = json.load(file) # Process project_data and generate report return report
- Quality Management:
- Quality Control Logs: Record quality control checks in log files.
- Compliance Reports: Generate compliance reports by reading quality data from files.
Example:
pythondef log_quality_check(product_id, result): with open('quality_checks.log', 'a') as file: file.write(f"{datetime.now()},{product_id},{result}\n") def generate_compliance_report(start_date, end_date): report_data = [] with open('quality_checks.log', 'r') as file: for line in file: date, product_id, result = line.strip().split(',') if start_date <= date <= end_date: report_data.append((date, product_id, result)) # Process report_data and generate report return report
- Exception Handling
Exception Handling memungkinkan kita untuk menangani error yang mungkin terjadi saat runtime, memastikan program tetap berjalan atau berhenti dengan cara yang terkontrol.
Konsep Dasar:
- try: Blok kode yang mungkin menyebabkan exception
- except: Menangani exception spesifik
- else: Dieksekusi jika tidak ada exception
- finally: Selalu dieksekusi, baik ada exception atau tidak
- raise: Memunculkan exception secara manual
Syntax and Structure:
Basic try-except block:
pythontry:# Code that may raise an exceptionexcept ExceptionType:# Code to handle the exceptionFinally block:
pythontry:# Code that may raise an exceptionexcept ExceptionType:# Code to handle the exceptionfinally:# Code that will run no matter whatRaising exceptions:
pythonraise ExceptionType('Error message')
Advanced Techniques:
- Handling multiple exceptions:pythontry:# Code that may raise an exceptionexcept (ExceptionType1, ExceptionType2) as e:# Code to handle the exceptions
Contoh dasar:
pythontry: result = 10 / 0 except ZeroDivisionError: print("Tidak bisa membagi dengan nol") else: print("Hasil:", result) finally: print("Operasi selesai")
Comments
Post a Comment