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

วิธีอ่านเฉพาะบรรทัดแรกของไฟล์ใน Python

เปิดไฟล์ read mode เรียก readline():

f = open('my_file.txt', 'r')
line = f.readline()
print(line)
f.close()

ปลอดภัยกว่า ใช้ with:

with open('my_file.txt', 'r') as f:
    print(f.readline())