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

วิธีเขียน Binary Data ลงไฟล์ด้วย Python

"Binary files" คือไฟล์ที่รูปแบบไม่ได้ประกอบด้วยอักขระอ่านได้ เช่น รูปภาพ JPEG/GIF, เสียง MP3, หรือเอกสาร Word/PDF ใน Python ไฟล์เปิดใน text mode โดย default ต้องเพิ่ม 'b' ใน mode เพื่อเปิดใน binary mode

ตัวอย่าง

f = open('my_file', 'w+b')
byte_arr = [120, 3, 255, 0, 100]
binary_format = bytearray(byte_arr)
f.write(binary_format)
f.close()

โค้ดนี้เปิดไฟล์ใน binary write mode และเขียนเนื้อหา byte_arr เป็น bytes ลงไฟล์ binary