习题17 更多文件操作

这节似乎是 copy 文件,主要是从一个 from file 到一个 to file 的 copy

先给代码

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)
# We could do these two on one line too, how?
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 RETURN to continue , CTRL-C to abort."
raw_input()

out_file = open(to_file ,'w')
out_file.write(indata)

print "Alright ,all done."

out_file.close()
in_file.close()

这里主要是新建了一个文件 mew-file.txt 然后把 test.txt 里面的东西 copy 到这个文件之中

结果是这样的



然后我们运行 cat 命令,可以看到确实是 copy 过去了



在语句

print "Does the output file exist? %r" % exists(to_file)
之中有一个 exists 命令,这个命令把 to_file 当做是参数,如果 to_file 存在,那么返回一个True,如果不存在则返回 False


==========================================================================================

附加练习

1. import 到底有啥用

搜了一下


import语句作用就是用来导入模块的,它可以出现在程序中的任何位置。

使用方法例如:
import math       #入导math模块
math.floor()        #调用math模块中的floor()函数

如果要同时导入多个模块,只需要在模块名之前用逗号进行分隔:
import module1,module2,module3.......


2.其实就是删一些print

3.我回头试试,,,如果我还想得起来的话

4.5.cat代替品?我直接打开行不行

6.close()是为了释放资源。






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值