您的位置:首页 > 编程语言 > Python开发

习题17 更多文件操作

2016-07-23 16:14 656 查看
这节似乎是 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()是为了释放资源。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python