Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tham số file trong hàm print() của Python

Hàm print() không chỉ in ra màn hình mà còn có thể ghi trực tiếp vào file hoặc luồng xuất (output stream) nhờ tham số file.

In ra file

Mở file ở chế độ ghi ('w'), truyền đối tượng file vào tham số file của print(). Các đối số khác sẽ được ghi vào file thay vì màn hình.

Ví dụ

Newfile = open("exam_score.txt", "w")
exam_name = "Degree"
exam_date = "2-Nov"
exam_score = 323
print(exam_name, exam_date, exam_score, file=Newfile, sep=",")
Newfile.close()

Kết quả

File exam_score.txt chứa: Degree,2-Nov,323.

In ra lỗi chuẩn (stderr)

Truyền sys.stderr vào tham số file để in ra luồng lỗi chuẩn.

Ví dụ

import sys
Newfile = open("exam_score.txt", "w")
exam_name = "Degree"
exam_date = "2-Nov"
exam_score = 323
print(exam_name, exam_date, exam_score, file=sys.stderr, sep=",")
Newfile.close()

Kết quả

Dòng Degree,2-Nov,323 xuất hiện trên stderr.