这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!
文中例题:
from sys import argv
from os.path import exists
script, frome_file, to_file = argv
print "Coping from %s to %s" % (frome_file, to_file)
# we could do these two on one line too, how?
input = open(frome_file)
indata = input.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file,'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()
运行截图:
习题答案:
1、
例题中的
from os.path import exists
意义:os.path.exists(path) #路径存在则返回True,路径损坏返回False
其实例题的意思就是一开始先得到两个文件名作为参数,然后打开已经编辑好的file,并且file.read()。再len(file)这个文件的大小。然后检查另一份file是否存在–exists(file)。这个函数返回bool类型。最后打开这份文件并且进行file.write(),内容就是第一份file中的数据。别忘记了file.close(),在上一章中介绍close()就类似保存退出。
2、代码如下:
# -- coding: utf-8 --
from sys import argv
script, frome_file, to_file = argv
print "Coping from %s to %s" % (frome_file, to_file)
# 这里试着回答作者的问题,我是这样写的,不知道有没有错,能运行就是了
indata = open(frome_file).read()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
open(frome_file).close()
删减的比较多,个人认为,只要告诉使用这你要做的事就好了,反正你检测存不存在,即使不存在你也创建一个出来了,就没必要说出来了。
3、代码如下:
# -- coding: utf-8 --
from sys import argv
script, frome_file, to_file = argv
#这只是想告诉大家,文件我一开始是清空了
open(to_file, 'w').truncate()
open(to_file, 'w').write(open(frome_file).read())
运行结果以及运行后的文件截图:
6、我之前学c++的时候是为了释放资源,我觉得对于python应该也一样的效果。要不然一直占着资源不释放,其他要用资源的进不来就不好了。当然,作者在上一章也说过,.close()相当于保存退出,也就是我们之前写的东西都在缓存中,并为真正写到文件中的意思。