Context Managers
Context managers จัดการ resources อัตโนมัติ ช่วยให้ setup และ cleanup ถูกต้องเสมอ
with Statement
Section titled “with Statement”with statement ใช้กับ context managers เพื่อจัดการ resources
# การใช้ with กับไฟล์ (ตัวอย่างที่พบบ่อยที่สุด)# with open('file.txt', 'r') as f:# content = f.read()# ไฟล์ถูกปิดอัตโนมัติเมื่อออกจาก with block
# เทียบกับการเขียนแบบเดิม# f = None# try:# f = open('file.txt', 'r')# content = f.read()# finally:# if f:# f.close()
# with ง่ายกว่าและปลอดภัยกว่ามากprint("with statement ensures proper cleanup")เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google