习题 17:更多文件操作
目标与感悟:
•复制文本内容至其他文件中
ex17.py
#-*-coding: utf-8-*-
from sys import argv
'''
此处引用了新的内置函数,exists函数是检查括号内字符串所代表的文件名的文件是否存在,
存在返回True,不存在返回False。
os.path os.path模块主要用于文件的属性获取,在编程中经常用到
'''
from os.path import exists
script, from_file,to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()
#len(),则是用于传递字符串的长度。
print "The input file is %d bytes long" %len(indata)
#此处使用exists验证新文件是否已经存在。
print"Does the output file exist? %r" % exists(to_file)
print"Ready, hit RETURN to continue,CTRL-C to abort."
#此处的raw_input()我还是不是特别理解,只知道大概是询问下一步是否继续。稍后做个简化测试。
raw_input()
#将open函数得到的结果(是一个文件,而不是文件的内容)赋值给in_file。
out_file = open(to_file, 'w')
#使用read函数读取文件内容,并将文件内容赋值给indata。
out_file.write(indata)
print "Alright, all done."
#最后保存关闭。
out_file.close()
in_file.close()
运行结果:
•很明显看出不同来了,对比2次运行结果,通过exists(to_file)来进行了一次判定,因为第一次运行时候文件不存在,所以第一次是false,第二次是true
感悟与自我测试:
自己参照原文,简化写个脚本吧。
ex17_1.py
#-*-coding:utf-8-*-
from sys import argv
from os.path import exists
script, from_file,to_file = argv
print"Copy,from %r to %r" %(from_file,to_file)
in_file = open(from_file)
read_file = in_file.read()
print "%d" %len(read_file)
print "Is exist? %r" %exists(to_file)
raw_input("Continue?")
out_file = open(to_file,'w')
out_file.write(read_file)
print "Allright!"
out_file.close()
in_file.close()
'''
总结下最关键的4个句子:
in_file = open(from_file)
read_file = in_file.read()
out_file = open(to_file,'w')
out_file.write(read_file)
翻译过来就是:
打开源文件
读取源文件
打开/新建目标文件
写入目标文件
'''
运行结果:
是的,看起来还不够简洁,让我们来个最不友好的简单脚本。
ex17_2.py
#-*-coding:utf-8-*-
from sys import argv
script, from_file,to_file = argv
in_file = open(from_file)
read_file = in_file.read()
out_file = open(to_file,'w')
out_file.write(read_file)
运行结果: