Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน open() ใน Python ทำอะไร?

open() เปิดไฟล์:

f = open('my_file', 'r+')
my_file_data = f.read()
f.close()

อาร์กิวเมนต์ 1: ชื่อไฟล์, อาร์กิวเมนต์ 2: โหมด (mode)

  • r - อ่าน
  • r+ - อ่าน/เขียน
  • w - ทับ (เขียน)
  • a - ต่อท้าย

OS มอบ file handle ต้อง close() ใช้ with ปิดอัตโนมัติ:

with open('my_file', 'r+') as f:
    my_file_data = f.read()