python - 如何在 Python 中读取文件的最后一行?

标签 python python-3.x python-2.7 file

我有两个要求。

第一个要求-我想读取文件的最后一行并将最后一个值赋给 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/

相关文章:

python - 如何读取夹在某个字符之间的数据(Python 3.3)

python-2.7 - PyMC3的贝叶斯推断。编译错误。

python - 请求 : Explanation of the . 文本格式

python - 使用 python 2.4 计算 CSV 文件中的列数

python - 如何减少二维连接域上的集成的集成时间

Python py2exe 导入错误 : MemoryLoadLibrary failed loading glib\_glib. pyd

python - 需要帮助优化代码,无法决定使用 dataframe 进行排序还是 mysql

python - 如何使用线程进行多个 GET 请求并进行比较

python - 根据第二个列表中的元素对列表进行排序和过滤

Python 扩展 - 有效地构造和检查大整数