在Python中从文件的特定点加载特定长度的文件
我有一个科学计划的输出,其中包含一个表的一些实例,看起来像:在Python中从文件的特定点加载特定长度的文件,python,string,Python,String,我有一个科学计划的输出,其中包含一个表的一些实例,看起来像: Standard orientation: --------------------------------------------------------------------- Center Atomic Atomic Coordinates (Angstroms) Number
Standard orientation:
---------------------------------------------------------------------
Center Atomic Atomic Coordinates (Angstroms)
Number Number Type X Y Z
---------------------------------------------------------------------
1 7 0 -2.365589 -0.297051 1.870038
2 6 0 -2.931493 0.222141 0.571475
3 6 0 -2.646169 -0.877981 -0.469921
我需要找到该表最后一次出现的行号。现在我想出了一个局部解决方案——逐行读取文件,颠倒顺序,找到“标准方向:”短语。然后从它的索引中获取行号
f=open(“file.out”、“r”)
行=f.读行()
行。反向()
索引=行。索引(“标准方向:”)
打印(长度(行)-索引-1)
问题是我得到一个错误,在我的文件中没有字符串“Standard orientation:”(当超过100时)。您可以找到最后一个表的行号,如下所示:
with open("file.out", "r") as f:
lines = f.readlines()
lines.reverse()
row = 0
for index, line in enumerate(lines):
if "Standard orientation:" in line:
row = index
break
row = len(lines) - row # this will refer to a row with the "Standard orientation:" phrase
print(row)
在这里,我在每一行中查找该短语,因为该行可能包含一些其他字符以及我们正在查找的短语。您可以找到最后一个表的行号,如下所示:
with open("file.out", "r") as f:
lines = f.readlines()
lines.reverse()
row = 0
for index, line in enumerate(lines):
if "Standard orientation:" in line:
row = index
break
row = len(lines) - row # this will refer to a row with the "Standard orientation:" phrase
print(row)
在这里,我在每一行中查找该短语,因为该行可能包含一些其他字符以及我们正在查找的短语。index()不返回结果,因为每一行不仅包含文本(可打印字符),还包含空白字符(空格、换行符等)
最简单的解决方案是在字符串中搜索子字符串“标准方向”:
string_to_search = "Standard orientation:"
f = open("file.out", "r")
for i, line in enumerate(reversed(f.readlines())):
if string_to_search in line:
print(len(lines) - i - 1)
break
index()不返回结果,因为每行不仅包含文本(可打印字符),还包含空格字符(空格、换行符等)
最简单的解决方案是在字符串中搜索子字符串“标准方向”:
string_to_search = "Standard orientation:"
f = open("file.out", "r")
for i, line in enumerate(reversed(f.readlines())):
if string_to_search in line:
print(len(lines) - i - 1)
break