Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将队列保存到文件_Python_Json_Python 2.7_File Io_Queue - Fatal编程技术网

Python 将队列保存到文件

Python 将队列保存到文件,python,json,python-2.7,file-io,queue,Python,Json,Python 2.7,File Io,Queue,我的目标是有一个文本文件,允许我将数据追加到末尾,并从文件中检索和删除第一个数据条目。本质上,我想使用文本文件作为队列(先进先出)。我想到了两种方法来实现这一点,但我不确定哪种方法更具蟒蛇式和效率。第一种方法是使用json库 import json def add_to_queue(item): q = retrieve_queue() q.append(item) write_to_queue(q) def pop_from_queue(): q = re

我的目标是有一个文本文件,允许我将数据追加到末尾,并从文件中检索和删除第一个数据条目。本质上,我想使用文本文件作为队列(先进先出)。我想到了两种方法来实现这一点,但我不确定哪种方法更具蟒蛇式和效率。第一种方法是使用json库

import json

def add_to_queue(item):
    q = retrieve_queue()
    q.append(item)
    write_to_queue(q)


def pop_from_queue():
    q = retrieve_queue()
    write_to_queue(q[1:])
    return q[0]


def write_to_queue(data):
    with open('queue.txt', 'w') as file_pointer:
        json.dump(data, file_pointer)


def retrieve_queue():
    try:
        with open('queue.txt', 'r') as file_pointer:
            return json.load(file_pointer)
    except (IOError, ValueError):
        return []
看起来很干净,但每次写/读时都需要对所有json数据进行序列化/反序列化,即使我只需要列表中的第一项

第二个选项是调用
readlines()
writelines()
来检索数据并将其存储在文本文件中

def add_to_queue(item):
    with open('queue.txt', 'a') as file_pointer:
        file_pointer.write(item + '\n')


def pop_from_queue():
    with open('queue.txt', 'r+') as file_pointer:
        lines = file_pointer.readlines()
        file_pointer.seek(0)
        file_pointer.truncate()
        file_pointer.writelines(lines[1:])
        return lines[0].strip()

这两种方法都很好,所以我的问题是:实现“文本文件队列”的推荐方法是什么?使用json是否比自己读写文件“更好”(更Pythonic/更快/内存效率更高)?基于问题的简单性,这两种解决方案似乎都相当复杂;我是否缺少一个更明显的方法来完成此操作?

您何时需要文本文件?例如,您是否可以实现一个上下文管理器类,该类在运行时将队列保存在内存中,然后将其保存到
\uuuuuu exit\uuuuuu
上的文件中?该脚本正在由cronjob运行。每次执行只需要从队列中读取一次。当队列耗尽时,它调用函数获取更多数据,然后将其存储在队列中。事实上,我不认为我需要一次向队列中添加一个项目(但是为了完整性,我将其包含在我的问题中)。