提取非常长的txt文件的最后一行

时间:2015-08-21 15:59:53

标签: python python-2.7

我有一个包含数据的非常长的文件(" text.txt")和一个包含1行的文件,这是text.txt的最后一行。这条单行应该每10分钟覆盖一次(由一个简单的chronjob完成),因为text.txt每10分钟收到一行。

基于我在stackoverflow上找到的其他代码片段,我目前运行此代码:

#!/usr/bin/env python

import os, sys

file = open(sys.argv[1], "r+")

#Move the pointer (similar to a cursor in a text editor) to the end of the file. 
file.seek(0, os.SEEK_END)

#This code means the following code skips the very last character in the file - 
#i.e. in the case the last line is null we delete the last line 
#and the penultimate one
pos = file.tell() - 1

#Read each character in the file one at a time from the penultimate 
#character going backwards, searching for a newline character
#If we find a new line, exit the search
while pos > 0 and file.read(1) != "\n":
    pos -= 1
    file.seek(pos, os.SEEK_SET)

#So long as we're not at the start of the file, delete all the characters ahead of this position
if pos > 0:
    file.seek(pos, os.SEEK_SET)
    w = open("new.txt",'w')
    file.writelines(pos)
    w.close()

file.close()

使用此代码我收到错误:

  

TypeError:writelines()需要一个可迭代的参数

(当然)。使用file.truncate()时,我可以删除原始文件中的最后一行;但是我想保留它并将最后一行提取到new.txt。但是,在使用file.seek时,我无法理解这是如何工作的。所以我在代码的最后部分需要帮助。

带有file.readlines()

lines[:-1]无法正常使用这些大文件。

4 个答案:

答案 0 :(得分:1)

不确定为什么要打开w,只关闭它而不做任何事情。如果您希望new.txt包含file的所有文字,从pos开始到结尾,那么如何:

if pos > 0:
    file.seek(pos, os.SEEK_SET)
    w = open("new.txt",'w')
    w.write(file.read())
    w.close()

答案 1 :(得分:1)

根据您的代码,1是一个整数,用于表示文件末尾的第一个pos的位置。

你无法做到 - \n,因为writelines需要一个行列表。但是file.writelines(pos)是一个整数。

您也想写信给pos,因此您应该使用new.txt文件来撰写,而不是w。示例 -

file

答案 2 :(得分:0)

以下方法如何:

max_line_length = 1000

with open(sys.argv[1], "r") as f_long, open('new.txt', 'w') as f_new:
    f_long.seek(-max_line_length, os.SEEK_END)
    lines = [line for line in f_long.read().split("\n") if len(line)]
    f_new.write(lines[-1])

这将寻找几乎文件的末尾并读取文件的剩余部分。然后将其拆分为非空行,最后一个条目写入new.txt

答案 3 :(得分:0)

以下是如何将文件的最后两行拖尾到列表中:

import subprocess
output = subprocess.check_output(['tail', '-n 2', '~/path/to/my_file.txt'])
lines = output.split('\n')

现在,您可以从列表lines中获取所需信息。

相关问题