模块名称:测试.py python版本:3 如有错误,敬请指出
#加分习题16
#1
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.")
input("?")
print("Opening the file...")
target = open(filename,'w')#target 目标 以写入模式打开
print("Truncating the file.Goodbye")
target.truncate()#清空文档,这部分会清空你test之前写入的内容
print("Now I'm going to ask you for three lines.")
line1 = input("line 1 : ")
line2 = input("line 2 : ")
line3 = 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()#关闭文件
#2
target = open(filename)#不要忘了重新open一下
print(target.read())
target.close()
#3
target = open(filename,'w')#没有清空文档,以'w'打开会覆盖原有文件
line1 = input("line 1 : ")
line2 = input("line 2 : ")
line3 = input("line 3 : ")
target.write("%s\n%s\n%s\n"%(line1,line2,line3))
#4略
#5略
运行结果:
PS C:\Users\user2\AppData\Local\Programs\Python\Python37\笨办法学python> python 测试.py test.txt
We're going to erase 'test.txt'.If you don't want that,hit CTRL-C(^C).
If you do want that,hit RETURN.
?
Opening the file...
Truncating the file.Goodbye
Now I'm going to ask you for three lines.
line 1 : 1
line 2 : 2
line 3 : 3
I'm going to write these to the file.
And finally,we close it.
1
2
3
line 1 : h
line 2 : u
line 3 : i