在Python上的一个文件中存储最后15个值

2024-06-08 12:15:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做一个程序,接收一个整数并将其存储在一个文件中。当它有15个(或20个,确切的数字并不重要),它将覆盖它写的第一个。它们可能在同一条线上,也可能在一条新线中。 这个程序从传感器读取温度,然后我将在一个带有php图表的站点上显示它。在

我考虑过每半小时写一个值,当它有15个值,并且有一个新值出现时,它会覆盖最旧的值。在

我在保存值时遇到了问题,我不知道如何用新行将列表保存为一个字符串,它可以保存两个新行,我是python新手,我真的迷路了。在

这不起作用,但它是我想做的事情的“样本”:

import sys
import os

if not( sys.argv[1:] ):
    print "No parameter"
    exit()

# If file doesn't exist, create it and save the value
if not os.path.isfile("tempsHistory"):
    data = open('tempsHistory', 'w+')
    data.write( ''.join( sys.argv[1:] ) + '\n' )
else:
    data = open('tempsHistory', 'a+')
    temps = []
    for line in data:
        temps += line.split('\n')
    if ( len( temps ) < 15 ):
        data.write( '\n'.join( sys.argv[1:] ) + '\n' )
    else:
        #Maximum amount reached, save new, delete oldest
        del temps[ 0 ]
        temps.append( '\n'.join( sys.argv[1:] ) )
        data.truncate( 0 )
        data.write( '\n'.join(str(e) for e in temps) )
data.close( )

我正在使用“”迷路。加入和\n等。。。我的意思是,我不必写一个字符串。如果我使用'\n'.join,我想它可以节省两倍的空间。 提前谢谢你!在


Tags: 字符串import程序dataifossavesys
3条回答

你想要的是

values = open(target_file, "r").read().split("\n")
# ^ this solves your original problem as readline() will keep the \n in returned list items
if len(values) >= 15:
    # keep the values at 15
    values.pop()
values.insert(0, new_value)
# push new value at the start of the list
tmp_fd, tmp_fn = tempfile.mkstemp()
# ^ this part is important
os.write(tmp_fd, "\n".join(values))
os.close(tmp_fd)
shutil.move(tmp_fn, target_file)
# ^ as here, the operation of actual write to the file, your webserver is reading, is atomic
# this is eg. how text editors save files

但无论如何,我建议您考虑使用一个数据库,无论是postgresql、redis、sqlite或任何能让您的船漂浮的东西

您应该尽量不要将存储在列表中的数据与在字符串中设置格式相混淆。数据不需要“\n”s

所以公正临时附加(系统argv[1:])就够了。在

此外,您不应自行序列化/反序列化数据。看看pickle。这比你自己读/写列表要简单得多。在

我想你想要的是这样的:

import sys 

fileTemps = 'temps'

with open(fileTemps, 'rw') as fd:
    temps = fd.readlines()

if temps.__len__() >= 15:
    temps.pop(0)

temps.append(' '.join(sys.argv[1:]) + '\n')

with open(fileTemps, 'w') as fd:
    for l in temps:
        fd.write(l)

首先打开文件进行阅读。这个fd.readlines公司()调用将为您提供文件中的行。然后检查大小,如果行数大于15,则弹出第一个值并附加新行。然后你把所有的东西都写进一个文件。在

在Python中,通常,当您从一个文件中读取时(例如使用readline())会给您一个末尾带有'\n'的行,这就是为什么会出现两个换行符的原因。在

希望这有帮助。在

相关问题 更多 >