编辑大型文本文件中的单行

Rob*_*p87 6 python text-files

所以我需要记录一组4个整数,它们的值在每天的每一秒都不同.即:

#Here the values are initialized to the same value, however they will change as samples are taken
data = [[.25 for numData in range(4)] for numSecs in range(86400)]
Run Code Online (Sandbox Code Playgroud)

现在显然是一个二维数组(gah它的python,LIST),其第一个索引长度是86400是非常不切实际的.相反,我想创建一个文本文件,其格式为86400行:

numSec data0 data1 data2 data3

0 .25 .25 .25 .25
1 .25 .25 .25 .25
2 .25 .25 .25 .25
...
Run Code Online (Sandbox Code Playgroud)

并且在采集样本时,我希望能够编辑此文件,不,我希望能够编辑numSec =采样的第二个文件的行.例如,以numSec = 2(午夜后2秒)拍摄的样本将导致我的程序编辑该文件,以便:

0 .25 .25 .25 .25
1 .25 .25 .25 .25
2 .70 .10 .10 .10
...
Run Code Online (Sandbox Code Playgroud)

看起来很简单,我甚至阅读了一些帖子,演示了如何在文本文件中重写单个.问题是,它们都要求您读入整个文件.我不希望我的程序每秒读取86,400行.

因此,我们得出了一个问题:我是否可以在文本文件中读取一行,编辑它并将其写回文件,而无需每次都需要进行更改时读取整个文件?

PS我应该注意我正在运行Ubuntu 12.04(精确),这是用于ROS节点

PPS该程序将运行任意数天,因此可以多次读取和重写每个"第二"数据.我想使用文件的另一个原因是如果系统需要关闭,我想保存下次运行时的分发.

per*_*eal 3

您可能需要稍微修改一下,它假设所有线的长度相同。为此,我必须将第一列填充到固定宽度。但如果您不想填充,您应该能够计算特定行之前的 1,2,3,4,.. 数字的数量。

data = [[.25 for numData in range(4)] for numSecs in range(86400)]
length_line=0

def write_line(f, sec, data):
    line="{:6d}".format(sec) + " " +" ".join(
            ["{:.2f}".format(dd) for dd in data])+"\n"
    f.write(line)
    return len(line)

with open('output', 'w') as of:
    for i,d in enumerate(data):
        length_line=write_line(of, i, d)

with open('output', 'rb+') as of:
    # modify the 2nd line:
    n = 2
    of.seek(n*length_line)
    write_line(of, n, [0.10,0.10,0.10,0.10])
    # modify the 10th line:
    n = 10
    of.seek(n*length_line)
    write_line(of, n, [0.10,0.10,0.10,0.10])
Run Code Online (Sandbox Code Playgroud)