1 回答

TA貢獻1785條經驗 獲得超8個贊
因此,您最初可以簡化循環,如下所示:
with open("file.xvg", "r") as f:
for i, line in enumerate(f):
if i < 22:
# Skip up to line 22
continue
line = line.strip().split()
# It isn't clear what you want to append to `res`
if float(line[1]) >= 9.5:
print("P")
break
elif float(line[1]) <= 5.9:
print("R")
break
else:
print("N")
這將分析文件,而不是將其讀取到列表中并分析列表。break 語句將您帶出通過文件的循環。
如果目錄中有許多文件,則可以像這樣閱讀它們:
from pathlib import Path
for file in Path("/path/to/directory").rglob("*.xvg"):
with file.open("r") as f:
for i, line in enumerate(f):
# Same logic as above
pass
添加回答
舉報