这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!
文中例题:
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中的答案。
博主分享了自己在学习《笨办法学Python》时的习题答案,详细解答了书中出现的新概念,并邀请读者指出可能的错误和不足。内容包括文中例题的运行截图和文本截图。
4730

被折叠的 条评论
为什么被折叠?



