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

วิธี Truncate ไฟล์ที่ขนาดกำหนดใน Python

truncate([size]) ตัดขนาดไฟล์ ถ้าระบุ size จะตัดที่ size นั้น (สูงสุด) default คือ current position เรียก truncate() โดยไม่มี argument จะตัดที่ตำแหน่งปัจจุบัน

ตัวอย่าง

>>> # test.txt contents: ABCDE
>>> f = open('test.txt', 'r+')
>>> f.truncate(2)
>>> f.read()
'AB'

หมายเหตุ: ไม่ทำงานกับไฟล์ที่เปิดใน read-only mode