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

วิธีเขียนบรรทัดเดียวลง Text File ใน Python

ใช้ write เขียนบรรทัดเดียว:

ตัวอย่าง

f = open('myfile', 'w')
f.write('hi there\n')  # Python แปลง \n เป็น os.linesep เอง
f.close()  # ส่วนใหญ่ละได้ เพราะ destructor จะปิดให้

หรือใช้ print() (Python 2.6+):

from __future__ import print_function  # Python 2 เท่านั้น
print("hi there", file=f)

Python 3 ไม่ต้อง import print_function