我有两个要求。
第一个要求-我想读取文件的最后一行并将最后一个值赋给 python 中的一个变量。
第二个要求-
这是我的示例文件。
<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/>
<context:property-placeholder location="filename.txt"/>
我想从这个文件中读取内容,即 filename.txt,它将在 <context:property-placeholder location= .
之后.并且想将该值分配给 python 中的变量。
最佳答案
一个简单的解决方案,不需要将整个文件存储在内存中(例如使用 file.readlines()
或等效结构):
with open('filename.txt') as f:
for line in f:
pass
last_line = line
对于大文件,寻找文件末尾并向后移动以找到换行符会更有效,例如:
import os
with open('filename.txt', 'rb') as f:
try: # catch OSError in case of a one line file
f.seek(-2, os.SEEK_END)
while f.read(1) != b'\n':
f.seek(-2, os.SEEK_CUR)
except OSError:
f.seek(0)
last_line = f.readline().decode()
注意文件必须以二进制模式打开,否则,it will be impossible to seek from the end .
关于python - 如何在 Python 中读取文件的最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258499/