f.seek()和f.tell()读取文本文件的每一行 [英] f.seek() and f.tell() to read each line of text file

查看:993
本文介绍了f.seek()和f.tell()读取文本文件的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个文件并使用 f.seek() f.tell()

test.txt:

  abc 
def
ghi
jkl

我的代码是:

  f = open('test.txt','r')
last_pos = f.tell()#了解当前位置在文件
last_pos = last_pos + 1
f.seek(last_pos)#改变文件中的当前位置
text = f.readlines(last_pos)
打印文本

读取整个文件。



  f = open(...)$ b解决方案


$ b f.seek(last_pos)

line = f.readline()#no's'在readline()结尾处

last_pos = f.tell()

f.close()

last_pos 不是文件中的行号,它是从文件开始的字节偏移量 - th ere没有必要增加/减少它。


I want to open a file and read each line using f.seek() and f.tell():

test.txt:

abc
def
ghi
jkl

My code is:

f = open('test.txt', 'r')
last_pos = f.tell()  # get to know the current position in the file
last_pos = last_pos + 1
f.seek(last_pos)  # to change the current position in a file
text= f.readlines(last_pos)
print text

It reads the whole file.

解决方案

ok, you may use this:

f = open( ... )

f.seek(last_pos)

line = f.readline()  # no 's' at the end of `readline()`

last_pos = f.tell()

f.close()

just remember, last_pos is not a line number in your file, it's a byte offset from the beginning of the file -- there's no point in incrementing/decrementing it.

这篇关于f.seek()和f.tell()读取文本文件的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆