系统:mac os 10.14
Python: 2.7.10
版本:《笨办法学Python》(第四版)
基本习题
1. 完成基本习题
(1) 根据题目,编辑以下内容:
from sys import argv #引入Python的argv功能
script, filename = argv #解包,将argv中的参数分别赋予变量名
#以下均为文本输出
print "We're going to erase %r." %filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you want that, hit RETURN."
#用“?”引导输入
raw_input("?")
print "Opening the file..."
target = open(filename, 'w') #打开、并可写文件
print "Truncating the file. Goodbye!"
target.truncate() #清空文件对象target
print "Now I'm going to ask you for three lines."
# 获取外部输入,并将值赋给变量
line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")
print "I'm going to write these to the file."
target.write(line1) #将变量写入文件对象target
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close() #关闭文件
输出结果如图所示:
加分习题
1. 如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己 理清思路。
就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。已备注在代码中。
2. 写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。
from sys import argv
script, filename = argv
file = open(filename)
print file.read()
3. 文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打印出来,
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
4. 找出为什么我们需要给 open 多赋予一个 ‘w’ 参数。
提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。