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

ใช้พารามิเตอร์ file ใน print() เขียนข้อมูลลงไฟล์ใน Python


บทนำ

ฟังก์ชัน print() ไม่ได้พิมพ์หน้าจออย่างเดียว สามารถเขียนลงไฟล์หรือสตรีมเอาต์พุตอื่นได้ด้วยพารามิเตอร์ file

1. เขียนลงไฟล์

with open("exam_score.txt", "w") as f:
    exam_name = "Degree"
    exam_date = "2-Nov"
    exam_score = 323
    print(exam_name, exam_date, exam_score, file=f, sep=",")

# ไฟล์ exam_score.txt จะมีเนื้อหา: Degree,2-Nov,323

2. เขียนลง Standard Error (stderr)

import sys
print("Error message", file=sys.stderr)

3. เขียนลง StringIO (เก็บในหน่วยความจำ)

from io import StringIO
buffer = StringIO()
print("Hello", "World", file=buffer)
content = buffer.getvalue()  # "Hello World\n"

พารามิเตอร์ที่เกี่ยวข้อง

  • sep: ตัวคั่นระหว่างค่า (ค่าเริ่มต้น space)
  • end: ตัวอักษรท้าย (ค่าเริ่มต้น newline)
  • flush: บังคับเขียนทันที (ค่าเริ่มต้น False)