练习17:更多读写练习
来源:互联网 发布:python bytebuffer 编辑:程序博客网 时间:2024/05/29 17:00
本次实例代码是一份可以复制文件的脚本
#-*- coding:utf-8 -*-from sys import argv # 从sys库中引入argvfrom os.path import exists # 从os.path库中引入existsscript, from_file, to_file = argv # 解包argvprint "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 argvscript, file_in, file_out = argvfile_write = open(file_out,'wb')file_write.write(open(file_in, 'rb').read())file_write.close()
结果:
复制后文件大小与源文件一致:
文件正常打开:
以上,呼~
0 0
- 练习17:更多读写练习
- 练习25:更多练习
- exercise 25 更多更多练习
- 练习17——更多文件操作
- 习题24 更多练习
- exercise 24 更多练习
- Exercise 25: 更多更多的练习
- Exercise 24:更多的练习
- ListView下拉加载更多练习
- 练习7:打印更多字符串
- 文件读写小练习
- 注册表 读写练习
- C++文件读写练习
- 练习16:文件读写
- python 文件读写练习
- 练习9:更多打印 = =、
- 第24个python程序:更多练习
- 笨方法学Python 习题 25: 更多更多的练习
- 利用OpenSSL库对Socket传输进行安全加密
- shell脚本学习笔记 (流编辑器sed)
- 栈的数组表示
- Java设计模式(二) Decorator(装饰)模式及Java I/O引申
- 通过八叉树进行空间分割和搜索
- 练习17:更多读写练习
- 开源imageload的使用
- HDU-3081-Marriage Match II(最大流+并查集+二分)
- visual studio 2013和sql server数据库连接
- 基于 SoapUI 工具测试 Rest 服务
- [Android Studio系列(三)]Android Studio 编译、同步慢的解决方法
- IOS 给View添加阴影效果
- com.mchange.v2.ser.Indirector错误
- 剑指offer 用两个栈实现队列