问题描述
我正在编写一个脚本,它需要扫描文件,直到找到出现子字符串的行,保存该行开头的位置,然后再返回。我对python很陌生,所以我还没有取得太大的成功。这是我当前的代码:
with open("test.txt") as f:
pos = 0
line = f.readline()
while line:
if "That is not dead" in line:
pos = f.tell() - len(line.encode('utf-8'))
# pos = f.tell()
line = f.readline()
f.seek(pos)
str = f.readline()
print(str)
使用 test.txt:
That is not dead
Which can eternal lie
Till through strange aeons
Even Death may die
Sphinx of black quartz,judge my vow!
输出如下:
hat is not dead
[newline character]
我意识到我原来的 pos = f.tell()
给了我行的 end 的位置而不是开头,我找到了 this 详细说明如何获取字节的答案字符串的长度,但使用它会切断第一个字符。使用 utf-16 或 utf-16-le 分别给出 ValueError: negative seek position -18
或 ValueError: negative seek position -16
。我尝试使用 this 答案中的解决方案,使用以下代码:
with open("ctest.txt") as f:
pos = 0
line = f.readline()
while line:
if "That is not dead" in line:
print(line)
f.seek(-len(line),1)
zz = f.readline()
print(zz)
line = f.readline()
f.seek(pos)
str = f.readline()
print(str)
在 io.UnsupportedOperation: can't do nonzero cur-relative seeks
处给出 f.seek(-len(line),1)
有人可以指出我哪里出错了吗?
解决方法
Stefan Papp 建议在读取行之前保存位置,这是一个我没有考虑过的简单解决方案。调整后的版本:
with open("test.txt") as f:
pos = 0
tempPos = 0
line = f.readline()
while line:
if "That is not" in line:
pos = tempPos
tempPos = f.tell()
line = f.readline()
f.seek(pos)
str = f.readline()
print(str)
使用正确的输出:
That is not dead
[newline character]
谢谢,斯蒂芬。我想我对我的问题太深入了,无法清楚地思考它。 如果有比我所做的更好的遍历文件的方法,我很想知道,但这似乎有效。