python中文件读取read、指针位置tell、移动指针seek函数

 

001、文件对象read读入文件

>>> in_file = open("a.txt", "r")
>>> in_file.read()         ## 
'abcd\nefgh\ni\n'

 

002、文件对象tell 返回指针再文件中的位置

>>> in_file = open("a.txt", "r")        ## 打开文件
>>> in_file.tell()                      ## 返回文件指针当前的位置
0
>>> in_file.read()                      ## 读入文件
'abcd\nefgh\ni\n'
>>> in_file.tell()                      ## 返回指针当前的位置
12

 

003、文件对象seek移动指针

复制代码
>>> in_file = open("a.txt", "r")             ## 打开文件
>>> in_file.tell()                           ## 返回当前指针
0
>>> in_file.read()                           ## 读入文件
'abcd\nefgh\ni\n'
>>> in_file.tell()                           ## 返回当前指针位置
12
>>> in_file.seek(5,0)                        ## 从0开始偏移5
5
>>> in_file.tell()                           ## 返回当前指针位置
5
>>> in_file.read()                           ## 从指针位置读入文件
'efgh\ni\n'
复制代码

 

004、设定读入的字符数目

>>> in_file = open("a.txt", "r")           ## 打开文件
>>> in_file.read(5)                        ## 读入5个字符
'abcd\n'
>>> in_file.tell()                         ## 返回当前指针的位置
5

 。

 

posted @   小鲨鱼2018  阅读(396)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-07-03 2.3.4 设A为n阶方阵,满足AA^T = I, |A| < 0, 求|A + I|.
点击右上角即可分享
微信分享提示