《笨办法学python》加分习题17——我的答案

这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!

文中例题:

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()相当于保存退出,也就是我们之前写的东西都在缓存中,并为真正写到文件中的意思。

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值