2016-05-13 91 views
4

我正在从AWS S3下载带有boto3的文件,它是一个基本的JSON文件。Python 2.7中的错误文件描述符

{ 
    "Counter": 0, 
    "NumOfReset": 0, 
    "Highest": 0 
} 

我可以打开JSON文件,但是当我去倾倒回到同一文件中更改某些值后,我得到IOError: [Errno 9] Bad file descriptor

with open("/tmp/data.json", "rw") as fh: 
    data = json.load(fh) 
    i = data["Counter"] 
    i = i + 1 
    if i >= data["Highest"]: 
     data["Highest"] = i 
    json.dump(data, fh) 
    fh.close() 

我只是使用错误的文件模式,或者我这样做是不正确的?

+1

打开文件进行阅读,读取信息,进行更改,然后打开文件进行写入并转储。 – Keozon

+1

'rw'不存在。你正在寻找'r +'。 –

回答

6

两件事。它的r+而不是rw,如果你想覆盖以前的数据,你需要返回到文件的开头,使用fh.seek(0)。否则,将更改已更改的JSON字符串。

with open("/tmp/data.json", "r+") as fh: 
    data = json.load(fh) 
    i = data["Counter"] 
    i = i + 1 
    if i >= data["Highest"]: 
     data["Highest"] = i 

    fh.seek(0) 
    json.dump(data, fh) 
    fh.close() 

但是,这可能只覆盖部分数据。因此,使用w关闭并重新打开该文件可能是一个更好的主意。

with open("/tmp/data.json", "r") as fh: 
    data = json.load(fh) 

i = data["Counter"] 
i = i + 1 
if i >= data["Highest"]: 
    data["Highest"] = i 

with open("/tmp/data.json", "w") as fh: 
    json.dump(data, fh) 
    fh.close() 

无需fh.close(),这就是with .. as是。

+0

啊......嗯。谢谢! – mxplusb