python读取索引_Python | 从给定索引中读取文件(tell()和seek()的示例)

python读取索引

1)在Python文件处理中tell() (1) tell() in python file handling )

This method returns the current position of file pointer.

此方法返回文件指针的当前位置。

2)Python文件处理中的seek() (2) seek() in python file handling )

It set the position of file pointer at a specific position.

它将文件指针的位置设置在特定位置。

Syntax:

句法:

    file_object.seek(offset, whence)

Here,

这里,

  1. offset is the position of read/write pointer of the file.

    offset是文件的读/写指针的位置。

  2. whence is an optional argument, it has 3 values

    whence是可选参数,它具有3个值

    • 0 – to seek the file pointer from current position 0 –从当前位置查找文件指针
    • 1 – to seek the file pointer from starting position of the file1 –从文件的起始位置查找文件指针
    • 2 – to seek the file pointer from ending position of the file2 –从文件结束位置查找文件指针

Example:

例:

def main():
    fo = open("data.txt","wt")
    fo.write("Hello world, how are you? Here, you are learning python")
    fo.close()
    fo = open("data.txt","r")
    print("Name of the File : ",fo.name)
    str=fo.read(10)
    print("Read String is till 10       : ",str)
    pos= fo.tell()
    print("Current Position             : ",pos)
    str=fo.read(10)
    print("Read String is till next 10  : ",str)
    pos= fo.tell()
    print("Current Position             : ",pos)
    print()
    print("Sending Pointer back to Top")
    pos = fo.seek(0,0)
    print("Current Position             : ",pos)
    str=fo.read(25)
    print("Read String is till 25       : ",str)
    pos= fo.tell()
    print("Current Position             : ",pos)
    fo.close()
if __name__=="__main__":main()

Output

输出量

Name of the File :  data.txt
Read String is till 10       :  Hello worl
Current Position             :  10
Read String is till next 10  :  d, how are
Current Position             :  20

Sending Pointer back to Top
Current Position             :  0
Read String is till 25       :  Hello world, how are you?
Current Position             :  25


翻译自: https://www.includehelp.com/python/read-file-from-given-index-example-of-tell-and-seek.aspx

python读取索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值