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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP