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 好听的元旦简短祝福语