获取文件偏移-python与golang

创建一个测试文件,用golang和python逐行读取,输出每行的偏移,测试结果如下:

python

#!/usr/bin/env python

import sys
import os

def main():
    input = open("test.file");
    input.seek(0)

    while True:
        pos = input.tell()
        line = input.readline()
        line = line.strip() #trim the last "\n"
        if not line:
                break

        print pos

    return 0

if __name__ == '__main__':
    sys.exit(main())

 输出结果如下:

root:~ # python test.py
0
315
510
820
1130
1510
1898
2218
2538
2858
3178
3493
3807
4213
4625
5037
5449
5800

golang(go version go1.1 linux/amd64)

package main

import (
        "fmt"
        "os"
        "io"
        "bufio"
)

func main() {
        f, err := os.Open("test.file")
        if err != nil {
                fmt.Println(err)
                return
        }

        br := bufio.NewReader(f)

        for {
        _ , err := br.ReadBytes('\n')
        pos, _ := f.Seek(0, os.SEEK_CUR)
        if err == io.EOF {
                return
        } else {
                fmt.Println(pos)
        }
    }
}

输出结果如下

root:~ # go run test.go
4096
4096
4096
4096
4096
4096
4096
4096
4096
4096
4096
4096
7903
7903
7903
7903
7903
7903
7903
7903
7903
7903
7903
11944

 不知道是不是用了bufio的缘故,使得获取偏移不精确,还没找到解决办法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值