Python f.seek() 和 f.tell() 读取文本文件的每一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15594817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:30:15  来源:igfitidea点击:

f.seek() and f.tell() to read each line of text file

pythonfile-ioseektell

提问by John

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

我想打开一个文件并使用f.seek()and读取每一行f.tell()

test.txt:

测试.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.

它读取整个文件。

采纳答案by lenik

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_posis 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.

请记住,last_pos它不是文件中的行号,而是从文件开头的字节偏移量——增加/减少它没有意义。

回答by Sean Johnson

Is there any reason why you have to use f.tell and f.seek? The file object in Python is iterable - meaning that you can loop over a file's lines natively without having to worry about much else:

你有什么理由必须使用 f.tell 和 f.seek 吗?Python 中的文件对象是可迭代的——这意味着你可以在本地循环文件的行而不必担心其他很多事情:

with open('test.txt','r') as file:
    for line in file:
        #work with line

回答by lenik

A way for getting current position When you want to change a specific line of a file:

一种获取当前位置的方法当您想更改文件的特定行时:

cp = 0 # current position

with open("my_file") as infile:
    while True:
        ret = next(infile)
        cp += ret.__len__()
        if ret == string_value:
            break
print(">> Current position: ", cp)

回答by lotif

Skipping lines using islice works perfectly for me and looks like is closer to what you're looking for (jumping to a specific line in the file):

使用 islice 跳过行对我来说非常有效,并且看起来更接近您要查找的内容(跳转到文件中的特定行):

from itertools import islice

with open('test.txt','r') as f:
    f = islice(f, last_pos, None)
    for line in f:
        #work with line

Where last_pos is the line you stopped reading the last time. It will start the iteration one line after last_pos.

其中 last_pos 是您上次停止阅读的行。它将在 last_pos 后一行开始迭代。