您的位置:首页 > 编程语言 > Python开发

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

2017-08-15 23:10 267 查看
这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!

文中例题:

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中的答案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: