如何跳转到逐行循环的文件的下一行。下面的代码是跳过第二个循环中总计数的行,我希望它逐行跳过第一行所需的计数,这样我就可以从文件中提取正确的信息。
f = open("someTXT", "r")
lines = iter(f.readlines())
for line in lines:
thisLine = line.split(',')
if len(thisLine) > 3:
count = thisLine[4]
for i in range(1,int(count)):
next(lines)
print(line)
答案 0 :(得分:0)
这里有一些代码审查。不知道你在问什么。
使用上下文管理器打开文件:
with open("someTXT", 'rU') as f: # Universal newline flag, best practice
# lines = iter(f) # no need for this, my_file is an iterator
container = [] # use a container to hold your lines
for line in f:
test = test_for_correct_lines(line) # return True if keep and print
if test:
container.append(line)
# join the lines you want to keep with a newline and print them
print('\n'.join(container))