Python 檔案引數中的 print()?


常規使用 print() 函式可在命令列或互動式直譯器中顯示文字。但該函式也可寫入檔案或輸出流中。

列印到檔案

在該示例中,我們可以以寫模式開啟一個具有新檔名的檔案,然後在 print 函式中提及該檔名。要寫入檔案的值可作為引數傳遞到 print 函式中。

示例

Newfile= open("exam_score.txt", "w")

# variables
exam_name = "Degree"
exam_date = "2-Nov"
exam_score = 323

print(exam_name, exam_date, exam_score, file=Newfile , sep = ",")

# close the file
Newfile.close()

輸出

執行上述程式碼將為我們提供一個名為 exam_scores.txt 的檔案,其內容如下。

Degree,2-Nov,323

列印到標準輸出

我們還可以使用 print() 列印到標準輸出或標準錯誤。

示例

import sys
Newfile= open("exam_score.txt", "w")

# variables
exam_name = "Degree"
exam_date = "2-Nov"
exam_score = 323

print(exam_name, exam_date, exam_score, file=sys.stderr, sep = ",")

# close the file
Newfile.close()

輸出

執行上述程式碼的結果如下 −

Degree,2-Nov,323

更新日期:12-Jan-2021

780 次瀏覽

啟動你的 職業生涯

完成此課程可獲得認證

開始
廣告
© . All rights reserved.