Python程序输出到文件中


来源:Python参考手册

要将程序的输出送到一个文件中,需要在 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(),它们的工作方式完全相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值