当我逐行读取文件时,我想跳过 if 条件
;
之后以 [ word ]
开头的第一行,但我的代码给出了以下错误。我该如何修复这个错误?
AttributeError:'_io.TextIOWrapper'对象没有属性'next'
代码:
for line in open(inputfile, "r").readlines():
if "[ word ]" in line:
line = open(inputfile, "r").next()
您可以使用
startswith
检查该行如何开始,并使用 continue
移过该行
with open(inputfile, "r") as f:
for line in f:
if line.startswith(';'):
continue
...
你可以这样做:
with open(inputfile) as f:
for line in f:
if "[ word ]" in line:
line = f.readline() # 1
line
重新分配到 if
比较所使用的下一行。您应该只使用
continue
并添加变量来检查是否跳过第一行:
with open(inputfile, "r") as f:
skip_first = False
for line in f:
if line.startswith(';') and skip_first:
skip_first = True
continue