y23335793 发表于 2017-4-29 13:05:57

获取文件偏移-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的缘故,使得获取偏移不精确,还没找到解决办法。
页: [1]
查看完整版本: 获取文件偏移-python与golang