Python print()中的文件参数?
print()函数的常规用法是在命令行或交互式解释器中显示文本。但是相同的功能也可以写入文件或输出流。
打印到文件
在示例中,我们可以在写入模式下打开一个具有新文件名的文件,然后在打印功能中提及该文件名。可以将要写入文件的值作为参数传递给print函数。
例子
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()输出
运行上面的代码将为我们提供一个名为exam_scores.txt的文件,其中包含以下内容。
Degree,2-Nov,323
打印到标准输出
我们还可以使用它print()来打印标准输出或标准错误。
例子
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()输出
运行上面的代码给我们以下结果-
Degree,2-Nov,323
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短