您的位置:首页 > 其它

练习17:更多读写练习

2016-04-13 19:38 239 查看
本次实例代码是一份可以复制文件的脚本

#-*- coding:utf-8 -*-
from sys import argv # 从sys库中引入argv
from os.path import exists # 从os.path库中引入exists

script, from_file, to_file = argv # 解包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 contiune, 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() # 关闭源文件


OS库

python中的OS库主要是提供一些系统的功能,包含普遍的操作系统功能,与具体的平台无关。

其中os.path模块主要是提供一些目录与文件方面的操作功能

exists

exists()方法主要是用来判断文件是否存在,这个方法存在于os.path模块中

print "Does the output file exist? %r" % exists(to_file) # 检测目标文件是否存在


to_file为一个file object

len

len()函数的功能是返回一个文件的长度

print "The input file is %d bytes long" % len(indata) # 输出源文件长度


indata为文件内容

读取非文本文件

上面的实例脚本只可以正常读取文本文档,如果读取非文本文档的话会失败

文件长度读取失败:



复制后的文件大小错误:



文件无法打开:



这时可以用二进制的方式读取和写入文件

#-*- coding:utf-8 -*-

from sys import argv

script, file_in, file_out = argv

file_write = open(file_out,'wb')
file_write.write(open(file_in, 'rb').read())
file_write.close()


结果:

复制后文件大小与源文件一致:



文件正常打开:



以上,呼~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: