python习题16

Posted shadowyuriya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python习题16相关的知识,希望对你有一定的参考价值。

 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("
")
27 target.write(line2)
28 target.write("
")
29 target.write(line3)
30 target.write("
")
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 + " " + line2+ " " + line3+ " ") 

找出需要给open多传入一个‘w’参数的原因

w: 打开一个文件,只用于写入,如果这个文件已经存在,那就先打开,再从头编辑(原有内容会被删除),如果这个文件不存在,就创建。

如果用‘w’模式打开文件,其实是不需要target.truncate()的,因为回先清空文件原有内容再编辑。

 

以上是关于python习题16的主要内容,如果未能解决你的问题,请参考以下文章

python习题16

Python3练习题系列(03)

python16 习题

笨方法学Python——习题16

python 片段16

Python学习16 正则表达式3 练习题