我正在尝试编写一个文件输出解析器,但在如何打印最后一个字符串+下面N行数时遇到了问题。输出文件通常小于2MB,所以我应该不会有任何问题读取文件到内存,但如果有一个更优雅的解决方案,这将是很好的学习
我曾尝试将行保存到列表中,然后打印出最后出现的行,但它会将行拆分为单词,因此列表最终很难处理。我也有程序读取总行数需要提前打印,如果有其他解决方案比我所尝试的
def coord():
stdOrn = 'Standard orientation'
coord = {}
found = False
with open(name, 'r') as text_file:
for line in text_file:
if stdOrn in line:
found = True
elif 'Rotational constants (GHZ)' in line:
found = False
elif found:
coord = line
outFile.write(coord)
您可以将其作为字符串加载,使用
.rfind()
获取最后一次出现的索引,然后从最后一个索引执行字符串切片相关问题 更多 >
编程相关推荐