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

2024-05-05 03:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打开一个文件并使用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

它读取整个文件。


Tags: 文件thetotextinpostesttxt
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)

你为什么要用f.tell和f.seek?Python中的file对象是iterable,这意味着您可以在本地循环文件行,而不必担心其他问题:

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

好的,你可以用这个:

f = open( ... )

f.seek(last_pos)

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

last_pos = f.tell()

f.close()

请记住,last_pos不是文件中的行号,而是文件开头的一个字节偏移量--递增/递减没有意义。

相关问题 更多 >