栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python文件操作(六)-读取文件位置

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python文件操作(六)-读取文件位置

读取文件位置
  • 1.`tell()`返回文件的当前位置,即文件指针当前位置
  • 2.`seek()` 用于移动文件读取指针到指定位置

1.tell()返回文件的当前位置,即文件指针当前位置
with open("../logs/cc.log", 'rb') as can:
    print(can.read(100))#从文件读取指定100个字节数
    print("=============")
    print('当前读取文件位置为:', can.tell()) #100

执行结果:

2.seek() 用于移动文件读取指针到指定位置

语法: fileObject.seek(offset, whence)
-whence:可选,默认值为 0;给offset参数一个定义,表示要从哪个位置开始偏移;
- 0代表从文件开头开始算起;
- 1代表从当前位置开始算起;
- 2代表从文件末尾算起。

with open("../logs/cc.log", 'rb') as can:
    print(can.read(100))
    print("=============")
    # seek() 方法用于移动文件读取指针到指定位置
    print(can.seek(5, 0))  # 5
    print('当前读取文件位置为:', can.tell())  # 5

执行结果:

  • 0代表从文件开头开始算起
with open("../logs/cc.log", 'rb') as can:
    print(can.read(100))
    print("=============")
    # seek() 方法用于移动文件读取指针到指定位置
    print(can.seek(5, 1))  
    print('当前读取文件位置为:', can.tell())  

执行结果:

  • 1代表从当前位置开始算起
with open("../logs/cc.log", 'rb') as can:
    print(can.read(100))
    print("=============")
    # seek() 方法用于移动文件读取指针到指定位置
    print(can.seek(5, 2))  
    print('当前读取文件位置为:', can.tell())  

执行结果:

  • 2代表从文件末尾算起
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/303700.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号