我想搜索文件中的特定字符串,并根据我必须处理文件数据。
我知道如何通过打开文件2次来完成它。
这可以通过只打开一次文件来完成吗?
代码:
with open(path, "r") as _file:
for line in _file:
if "my_string" in line:
flag = True
break
with open(path, "r") as _file:
for line in _file;
if flag:
process line
...
else:
process differently
...
我试过了:
with open(path, "r") as _file:
for line in _file:
if "my_string" in line:
flag = True
break
for line in _file;
if flag:
process line
...
else:
process differently
...
但是这里第二个for循环从第一个循环离开的地方开始,它不会从第一行文件开始,这就是为什么它不在这里工作。
答案 0 :(得分:2)
您需要在第二个循环之前将文件位置倒回到开头。您可以使用_file.seek(0)
。