《笨办法学python》加分习题16——我的答案

博主分享了自己在学习《笨办法学Python》时的习题答案,详细解答了书中出现的新概念,并邀请读者指出可能的错误和不足。内容包括文中例题的运行截图和文本截图。

这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!

文中例题:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close()

运行截图:

这里写图片描述

文本截图:

这里写图片描述

习题答案:

1、文中代码出现了几个新的玩意:

# -- coding: utf-8 --
#open(路径/文件名,mode)
#mode:#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
#参考网址:http://www.cnblogs.com/dkblog/archive/2011/02/24/1980651.html  感谢
target = open(filename, 'w')
#文章开头点名,清空文档,慎用
target.truncate()
#写入文档
target.write(line1)

其他代码大家一路过来,肯定比我明白。
2、

from sys import argv

script, filename = argv

target = open(filename)

print "Let's read the file"
print "\n"
print target.read()

target.close()

3、我看了下write在file内的描述,他的参数只要是str就可以。所以改的代码如下:

target.write("%s\n%s\n%s"% (line1, line2, line3))

4、如1中的答案。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值