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

标签 python file-io seek tell

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

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

它读取整个文件。

最佳答案

好的,你可以使用这个:

f = open( ... )

f.seek(last_pos)

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

last_pos = f.tell()

f.close()

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

关于python - f.seek() 和 f.tell() 读取文本文件的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594817/

相关文章:

python - 如何将几千列插入到sqlite3中?

python - Python数据解析中的正则表达式

python - 如何将子进程对象传递给数组

java - 线程 "AWT-EventQueue-0"java.lang.NullPointerException中的异常和JTable问题

MySQL 在制表符分隔文件中包含逗号 (LOAD DATA INFILE)

Android:视频 SeekTo 错误

qt - 查看 QTextStream

python - 如何为 Pylons Controller 生成绝对 URL?

c# - 使用 C# 在 Windows CE 5.0 中创建文件

c++ - FFMPEG Seeking 带来音频伪像