【问题标题】:f.seek() and f.tell() to read each line of text filef.seek() 和 f.tell() 读取文本文件的每一行
【发布时间】:2013-03-24 03:22:46
【问题描述】:

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

test.txt:

abc
def
ghi
jkl

我的代码是:

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

它读取整个文件。

【问题讨论】:

  • 是的,readlines 就是这样做的。你的问题到底是什么?
  • 我需要逐行读取,将last_pos保存在某处,关闭文件,去打开文件,寻找last_pos,读取行,更新last_pos,关闭文件...
  • @John,如果您在子进程之间传递数据,请查看 StringIO 等。或者考虑使用数据库,例如MySQL

标签: python file-io seek tell


【解决方案1】:

好的,你可以使用这个:

f = open( ... )

f.seek(last_pos)

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

last_pos = f.tell()

f.close()

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

【讨论】:

  • lenik:我不明白你在stackoverflow.com/questions/15527617/… 的回答中的文件读取过程。所以我在这里提出一个新问题:)
  • 好的,事情就是这样。你有一个变量last_pos,它包含从文件开头的当前字节偏移量。你打开文件,seek() 到那个偏移量,然后使用readline() 读取一行。文件指针自动前进到下一行的开头。然后使用tell() 获取新的偏移量并将其保存到last_pos 以在下一次迭代中使用。请指出这个过程的哪一部分不清楚,我会尝试更详细地解释。
  • 不客气! =) 抱歉我第一次没有解释清楚
  • @lenik readlines 中的's' 不是拼写错误,它是另一种实现的方法 (doc)
【解决方案2】:

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

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

【讨论】:

  • 不不,我有特殊原因需要使用 f.tell 和 f.seek。
  • 您能告诉我们您的特殊原因吗?
  • @John - 为什么每次都需要关闭文件?
  • 另一个原因可能是需要保留当前到达的位置,以便以后能够继续读取(例如,假设您正在编写日志解析器)。
【解决方案3】:

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

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)

【讨论】:

    【解决方案4】:

    使用 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
    

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

    【讨论】:

    • 但是我怎样才能得到最后的位置呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2017-03-10
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多