在循环文件时,文件操作从第一次开始 [英] File operation starts again from first while looping through the file
问题描述
<$ c $ 我试图在文件中找到某个单词,并希望在满足条件时打印下一行。 c> f = open('/ path / to / file.txt','r')
lines = f.readlines()
对于行:
if'P / E 'in line:
n = lines.index(line)#get当前行的索引
print(lines [n + 1])#print the next line
a.close()
字符串P / E将在文件中出现4次,每次换行。
执行时,代码通常会在前两次出现P / E后打印下一行。然后再次返回并再次打印相同的前两个事件并退出。在前两次出现之后循环没有进行;
我检查了数据文件,看看我的输出是否是实际结果,但所有的下一行在P / E '。
我该如何解决这个问题?感谢。
list.index()
只有一个参数找到第一个事件。你必须给它一个起点来找到超过前一个索引的元素, list.index()
取第二个参数,告诉它从哪里开始搜索。 / p>
但是,您不需要使用 lines.index()
;这是非常低效的;它需要一个完整的扫描列表,测试每一行,直到找到匹配。
只要使用 小心, code> index + 1 不是一个有效的索引;如果你在 请注意,使用 I'm trying to find a certain word in a file and want to print the next line when a condition is met. The string 'P/E' will be present 4 times in the file, each time in a different line. When executed, the code prints the next line after the first 2 occurrences of 'P/E' normally. It then again goes back and prints the same first 2 occurrences again and exits. The loop is not proceeding after those first 2 occurrences; it kind of repeats the process and exits. I checked the data file to see if my output is the actual result, but all next lines are different after 'P/E'. How can I resolve this? Thanks. However, you don't need to use Just use the Be careful, there is a chance Note that using
这篇关于在循环文件时,文件操作从第一次开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! enumerate()
函数在循环中添加索引
pre $ 对于索引,行中枚举(行):
如果'P / E'在行中:
print(lines [index + 1])$ b $ b 行
列表的最后一行找到'P / E'
,你会得到一个 IndexError
。您可能需要添加和index + 1 < len(lines)
test。
file.readlines()
把所有的文件一次性存入内存。尽量避免这种情况;您可以直接在文件中循环,并记住前一行行:
with open(' /path/to/file.txt','r')as f:
previous =''
for line in f:
if'P / E'in previous:
print(line)#print this line
previous = line#记住下一次迭代
f = open('/path/to/file.txt','r')
lines = f.readlines()
for line in lines:
if 'P/E' in line:
n = lines.index(line) #get index of current line
print(lines[n+1]) #print the next line
a.close()
list.index()
with just one argument only finds the first occurrence. You'd have to give it a starting point to find elements past the previous index, list.index()
takes a second argument that tells it where to start searching from.lines.index()
; that's very inefficient; it requires a full scan through the list, testing each line until a match is found.enumerate()
function to add indices as you loop:for index, line in enumerate(lines):
if 'P/E' in line:
print(lines[index + 1])
index + 1
is not a valid index; if you find 'P/E'
in the very last line of the lines
list you'll get an IndexError
. You may have to add a and index + 1 < len(lines)
test.file.readlines()
reads all of the file into memory in one go. Try to avoid this; you could loop directly over the file, and remember the previous line instead:with open('/path/to/file.txt','r') as f:
previous = ''
for line in f:
if 'P/E' in previous:
print(line) # print this line
previous = line # remember for the next iteration