ex16-17---learn python the hard way
ex16
#-*- coding: UTF-8 -*- from sys import argv script,filename = argv print "We are going to erase %r." %filename print "If you don't want that ,hit control-C(^C)" print "If you do want that ,hit return." raw_input("?")#通过输入回车进入下一步 print "opening the file..." target = open(filename,'w')#默认情况下不加“w”,那么是以只读模式"r"打开的。 print "Truncating the file.Goodbye!" target.truncate()#清空文档 print"Now I am 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 file." #target.write("%s\n%s\n%s\n" %(line1,line2,line3)) target.write("\n") target.write(line2) target.write("\n") #注意换行符的斜杠方向\n target.write(line3) target.write("\n") print "And finally,we close it." target.close()
附加练习2中要求用read 和argv读取刚建的文件。
#-*- coding: UTF-8 -*- from sys import argv script,filename = argv txt = open(filename) print "Here is your file %r" %filename print txt.read()#读取之后打印才能看到 txt.close()
附加练习3,试着用一个target.write()打印line1-line3,可以使用字符串、格式化字符和转义字符
target.write("%s\n%s\n%s\n" %(line1,line2,line3))#这里注意括号里边的引号和括号
ex17
#-*- coding: UTF-8 -*- from sys import argv from os.path import exists script,from_file,to_file = argv print "Copying from %s to %s" %(from_file,to_file) in_file = open(from_file) indata = in_file.read() print "The input file is %d bytes long" %len(indata) print "Does the output file exist?%r" %exists(to_file) print"Ready,hit the return to continue,CTRL-C to abort." raw_input() out_file = open(to_file,"w") out_file.write(indata) print"Alrightm,all done." out_file.close() in_file.close() #to_file 是string,无法 close,关闭需要关闭 in_file #lens 可以用来读取文件的字节数 #exists 用来判断文件是否存在,然后返回布尔值
尽可能削减代码,自己重新写了一遍
#-*- coding: UTF-8 -*- from sys import argv from os.path import exists script,from_file,to_file = argv in_file = open(from_file) indata = in_file.read() out_file = open(to_file,"w") out_file.write(indata) out_file.close() in_file.close() #试图压缩代码,想把以下两句合并成一句 #in_file = open(from_file) #indata = in_file.read() #in_file = open(from_file,"r") #后来发现是错误的,因为这只是把文件以只读模式打开,并没有实现读的功能。 #-*- coding: UTF-8 -*- from sys import argv script,from_file,to_file = argv what_to_copy = open(from_file) out_file = open(to_file,"w") out_file.write(what_to_copy.read()) what_to_copy.close() out_file.close() #自己写的程序:实际上只需要这么几个流程:打开文件1-读取文件1-打开文件2-复制到文件2-关闭文件1/2
#尝试写成一行:
- from sys import argv
- script, from_file, to_file = argv
- open(to_file, 'w').write(open(from_file).read()
附加题中关于cat ,相同功能的还有在powershell下可以使用get-content [-Path]来读取txt文件