Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.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上重新加载JSON文件_Python_Json - Fatal编程技术网

在Python上重新加载JSON文件

在Python上重新加载JSON文件,python,json,Python,Json,我试图创建一个函数,每次修改JSON文件时,该函数都会更新(重新加载)JSON文件的内容 def fileWatcher(): global comandos, comandosText while True: f = open('comandos.json') content = f.read() f.close() if content != comandosText: print("Fi

我试图创建一个函数,每次修改JSON文件时,该函数都会更新(重新加载)JSON文件的内容

def fileWatcher():
    global comandos, comandosText
    while True:
        f = open('comandos.json')
        content = f.read()
        f.close()
        if content != comandosText:
            print("File was modified! Reloading it...")
            comandos = json.loads(content)
            comandosText = content
        time.sleep(0.5) #Adjust this to get the best performance
我(显然)已加载文件:

comandos = json.load(open('comandos.json'))
但是每次更新json时,我都必须停止python进程,以便再次加载它

--更新

脚本在一个循环中,我将它用作一个机器人(连接到电报,监听来自用户组的任何命令)

在这种情况下,当我“释放”新功能(新命令)时,我希望bot重新加载文件“comandos.json”上的所有内容,以获得电报频道上的新选项


谢谢您的时间。

当此文件更改时,您需要重新加载它。您可以使用诸如“知道何时重新加载”之类的功能。

编辑:此解决方案可多次读取文件,但不依赖于库,且与平台无关

请提供更多细节

以下是您可以使用的解决方案。当然还有其他选择,但我不知道确切的用例。我认为您希望在修改文件后重新加载它

def fileWatcher():
    global comandos, comandosText
    while True:
        f = open('comandos.json')
        content = f.read()
        f.close()
        if content != comandosText:
            print("File was modified! Reloading it...")
            comandos = json.loads(content)
            comandosText = content
        time.sleep(0.5) #Adjust this to get the best performance
然后在以后的主代码中

import time
import threading
import json
threading.Thread(target=fileWatcher).start()
这将在后台异步启动文件查看器,并在更新文件后更新
comandos


这段代码应该是现成的。

谢谢fameman,我已经更新了描述,希望能帮助理解我的问题:-)它已经开始工作了!感谢您的帮助和经验@fameman!!您可能想研究使用
mtime
我很高兴能帮助您。我只是不明白wjy我的答案被否决了。(旁白:没有必要添加“如果你需要更多帮助,请评论”-读者会知道这一点。根据我的签名等,我们喜欢简洁)。