Python程序设计-清华大学出版社-董付国第7章-文件操作.pptVIP

  • 82
  • 0
  • 约8.04千字
  • 约 43页
  • 2021-10-26 发布于河北
  • 举报

Python程序设计-清华大学出版社-董付国第7章-文件操作.ppt

7.4 二进制文件操作 数据库文件、图像文件、可执行文件、音频视频文件等等均属于二进制文件。 对于二进制文件,不能使用记事本或其他文本编辑软件进行正常读写。 7.4.1 使用struct模块 7.4.1 使用struct模块 例:使用struct模块读取二进制文件。 import struct f=open(sample_struct.dat, rb) sn=f.read(9) tu=struct.unpack(if?, sn) #从字节串sn中还原出1个整数、1个浮点数和1个布尔值,并返回元组 print(tu) n=tu[0] x=tu[1] bl=tu[2] print n=, n print x=, x print bl=, bl s=f.read(9) f.close() print s=, s 7.4.2 使用pickle模块 7.4.2 使用pickle模块 读取二进制文件: import pickle f=open(sample_pickle.dat, rb) n = pickle.load(f) #读出文件的数据个数 i=0 while in: x = pickle.load(f) print x i=i+1 f.close( ) 对象序列化 ObjectSequencing.py 7.5 文件操作 os模块常用的文件处理函数 函数 使用说明 access(path) 按照mode指定的权限访问文件 open(filename,flag[mode=0777]) 按照mode指定的权限打开文件,默认权限为可读、可写、可执行 chmode() 改变文件的访问权限 remove(path) 删除指定的文件 rename(src,dst) 重命名文件或目录 stat(path) 返回文件的所有属性 fstat(path) 返回打开的文件的所有属性 listdir(path) 返回path目录下的文件和目录 getcwd() 返回当前路径 7.5 文件操作 os.path模块常用的文件处理函数 函数名称 使用说明 abspath(path) 返回绝对路径 dirname(p) 返回目录的路径 exists(path) 判断文件是否存在 getatime(filename) 返回文件的最后访问时间 getctime(filename) 返回文件的创建时间 getmtile(filename) 返回文件的最后修改时间 getsize(filename) 返回文件的大小 isabs(path)、isdir(path)、isfile(path) 判断path是否为绝对路径、目录、文件 split(path) 对路径进行分割,以列表形式返回 splitext(path) 从路径中分割文件的扩展名 splitdrive(path) 从路径中分割驱动器的名称 walk(top,func,arg) 遍历目录 7.5 文件操作 import os import os.path os.path.exists(test1.txt) False os.rename(‘c:\\test1.txt’,‘d:\\test2.txt’) # 此时‘c:\\test1.txt’不存在 出错信息 os.rename(‘c:\\dfg.txt’,‘d:\\test2.txt’) # os.rename可以实现文件的改名和移动 os.path.exists(c:\\dfg.txt) False os.path.exists(d:\\dfg.txt) False os.path.exists(d:\\test2.txt) True path=d:\\mypython_exp\\new_test.txt os.path.dirname(path) d:\\mypython_exp os.path.split(path) (d:\\mypython_exp, new_test.txt) os.path.splitdrive(path) (d:, \\mypython_exp\\new_test.txt) os.path.splitext(path) (d:\\mypython_exp\\new_test, .txt) 7.5 文件操作 复制文件 import shutil shutil.copyfile(c:\\dir.txt,c:\\dir1.txt) 7.5 文件操作 列出当前目录下所有扩展名为pyc的文件 import os print [fname for fname in os.listdir(os.getcwd()) if os.path.isfile(fname) and fname.e

文档评论(0)

1亿VIP精品文档

相关文档