from sys import argv script,filename=argv #固定模式啦 print("we're going to erase %r."%filename) #打印 we're going to erase “filename” print("if you don't want that,hit CTRL-C(^C).") #打印if you don't want that,hit CTRL-C(^C). print("if you do want that,hit RETURN.") #打印if you do want that,hit RETURN. input("?") #提示符:? print("opening the file ...") #打印opening the file ... target=open(filename,'w+') #以写的模式打开“filename”并打印,再赋值给target print("truncating this file.Goodbye!") #打印truncating this file.Goodbye! target.truncate() #对target文件进行清空(truncate) print("now i'm going to ask you for three lines.") #打印:now i'm going to ask you for three lines. line1=input("line1:") line2=input("line2:") line3=input("line3:") ###输入line1/2/3的内容 print("i'm going to write these to the file.") #打印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.") #打印and finally,we close it. target.close() #关闭文件 #如果想要查看你自己编写的txt文件,要重新打开open,再read(记住一定是要先进行open!!) test=open("test.txt") print(test.read()) #对test执行read命令并且打印结果(这里并没有输入路径名,因为我也不知道刚才写的txt是存在哪里,demo里也没有。没想到这样成功了...) #——————————————————————分隔符————————————————————————加分训练(自己写一个文件) file=open('E:\python\demo\ex16+.txt','r+') #新建一个ex16+.txt file.truncate() line1=input(">>>>line1:") #更明显的用户提示 line2=input(">>>>line2:") line3=input(">>>>line3:") file.write("%s\n%s\n%s\n" %(line1, line2, line3)) #一个优化 #问题?file.write(line1+'\n'+line2+'\n'+line3+'\n')行不通唉 file=open('E:\python\demo\ex16+.txt') print(file.read()) #——————————————————————-第二种方法———————————————————— file=open('E:\python\demo\ex16+.txt','r+') file.truncate() line1=input(">>>>line1:") line2=input(">>>>line2:") line3=input(">>>>line3:") file.write(line1) file.write(line2) file.write(line3) nl='\n' file.write(nl+line1+nl+line2+nl+line3+nl) #这也是一种优化的办法,但是先输出所有的lines(在同一行),然后分行输出line1/2/3 file=open('E:\python\demo\ex16+.txt') print(file.read())
注意:最后做了一个优化,文件中重复的地方太多了。试着用一个target.write() 将line1, line2, line3 打印出来,使用字符串、格式化字符、以及转义字符。
推荐第一个方法,简单直接