[英]Read files of a line in python
我有一个名为 coord_1.xvg、coord_2.xvg 等的 1000 个文件。 我编写了一个程序,它读取每个文件的第二列,并在我提供的 if else 条件下给我 output。 它会打印一个 N 的列表,后跟 P 或 R,具体取决于先获得哪个并停止。
from pathlib import Path
for file in Path("/home/abc/xyz/coord/").rglob("*.xvg"):
with file.open("r") as f:
for i, line in enumerate(file):
if i < 22:
continue
line = line.strip().split()
if float(line[1]) >= 9.5:
print("P")
break
elif float(line[1]) <= 5.9:
print("R")
break
else:
print("N")
I want to read these files and print the value in the first column corresponding to the output P or R as the output along with P or R. 基本上,我需要找到停止读取该文件的行并提取与其对应的值。
在循环外创建一个变量,您可以在满足条件时将其设置为i
。
from pathlib import Path
stopped = 0
for file in Path("/home/abc/xyz/coord/").rglob("*.xvg"):
with file.open("r") as f:
for i, line in enumerate(file):
if i < 22:
continue
line = line.strip().split()
if float(line[1]) >= 9.5:
print("P")
stopped = i
break
elif float(line[1]) <= 5.9:
print("R")
stopped = i
break
else:
print("N")
另外,如果我理解正确,您的break
语句应该缩进到if
和elif
块内
如果您有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.