1 from sys import argv 2 3 script, filename = argv 4 5 print(f"We're going t o erase {filename}.") 6 print("If you don't want that, hit CTRL-(^C).") 7 print("If you do want that, hit RETURN.") 8 9 input("?") 10 11 print("Open the file...") 12 target = open(filename, 'w') 13 14 print("Truncating the file. Goodbye!") 15 target.truncate() 16 17 print("Now I'm going to ask you for three lines.") 18 19 line1 = input("line1: ") 20 line2 = input("line2: ") 21 line3 = input("line3: ") 22 23 print("I'm going to write these to the file.") 24 25 target.write(line1) 26 target.write("\n") 27 target.write(line2) 28 target.write("\n") 29 target.write(line3) 30 target.write("\n") 31 32 print("And finally, we close it.") 33 target.close()
写一段与上个习题类似的脚本,使用read和argv读取你刚刚新建的文件
1 from sys import argv 2 3 script, filename = argv 4 5 txt = open(filename) 6 print(f"现在我们来打开名字叫做{filename}的文件:") 7 print(txt.read())
这个文件中重复的地方太多了,试着用一个target.write()将line1,2和3打印出来,替换原先的六行代码,你可以用字符串 、格式化和转义字符
1 target.write(line1 + "\n" + line2+ "\n" + line3+ "\n")
找出需要给open多传入一个‘w’参数的原因
w: 打开一个文件,只用于写入,如果这个文件已经存在,那就先打开,再从头编辑(原有内容会被删除),如果这个文件不存在,就创建。
如果用‘w’模式打开文件,其实是不需要target.truncate()的,因为回先清空文件原有内容再编辑。