在Python中设置文件偏移

In the below program, we will learn,

在下面的程序中,我们将学习,

  1. How to set the offset in the file to read the content from the given offset/position?

    如何在文件中设置偏移量以从给定的偏移量/位置读取内容?

  2. How to find the offset/position of the current file pointer?

    如何找到当前文件指针的偏移量/位置?

Prerequisite:

先决条件:

Python程序演示在文件中设置偏移量的示例 (Python program to demonstrate example of setting offsets in a file)

# creating a file 
f = open('file1.txt', 'w')

# writing content to the file
# first line
f.write('This is line1.\n')
# second line
f.write('This is line2.\n')
#third line
f.write('This is line3.\n')

# closing the file
f.close()

# now, reading operations ....
# openingthe file
f = open('file1.txt', 'r')
# reading 10 characters
str = f.read(10);
print('str: ', str)

# Check current offset/position
offset = f.tell();
print('Current file offset: ', offset)

# Reposition pointer at the beginning once again
offset = f.seek(0, 0);
# reading again 10 characters
str = f.read(10);
print('Again the str: ', str)

# closing the file
f.close()

Output

输出量

str:  This is li
Current file offset:  10
Again the str:  This is li


翻译自: https://www.includehelp.com/python/setting-file-offsets-in-python.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值