首页 > 代码库 > python print输出到文件
python print输出到文件
要将程序的输出送到一个文件中,需要在 print 语句后面使用 >> 指定一个文件,如下所示:
principal = 1000 # 初始金额 rate = 0.05 # 利率 numyears = 5 # 年数 year = 1 f = open("out.txt", "w") # 打开文件以便写入 while year <= numyears: principal = principal * (1 + rate) print >> f, "%3d %0.2f" % (year, principal) year += 1 f.close()
语法只能用在 Python 2中。如果使用 Python 3,可将 print 语句改为以下内容:
print("%3d %0.2f" % (year, principal), file = f)
另外,文件对象支持使用 write() 方法写入原始数据。
f.write("%3d %0.2f\n" % (year, principal))
尽管这些例子处理的都是文件,但同样的技术也适用于标准的解释器输出流和输入流。可以从文件 sys.stdin 中读取用户输入,从文件 sys.stdout 将数据输出到屏幕上。
import sys
sys.stdout.write("Enter your name :")
name = sys.stdin.readline()
当然,在 Python 2 中,以上代码可以简化为:
name = raw_input("Enter your name :")
在 Python 3 中,raw_inupt() 函数叫做 input(),它们的工作方式完全相同。
python print输出到文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。