为什么python不会写入这个打开的文件?

问题描述:

我与蟒蛇(与语言相当缺乏经验)和文件I/O,并遇到下列错误修补跑:为什么python不会写入这个打开的文件?

ValueError: I/O operation on closed file.

非常简单,所以我在打印语句来检查的下降的outfile状态,看看发生了什么事情与我的代码:

import json 

data = {'thing1' : 'foo', 'thing2' : 'bar'} 

def writeToJSON(): 
    with open('data.json', 'w') as outfile: 
     print outfile.closed # outputs 'False', as expected 
     jsonifiedData = json.dumps(data, indent=4, sort_keys=True, separators=(',', ':'), ensure_ascii=False) 
     outfile.write(unicode(jsonifiedData)) # trace identifies this line as the issue 

writeToJSON() 

缩进看起来干净,所以这是怎么回事吗?

该文件在运行时显示为打开,但解释器立即抱怨在传送尽可能多的信息后写入该文件。

谢谢!

编辑:

添加整个文件。

此外,这是运行blurp.py时的完整输出:

False 
Traceback (most recent call last): 
File "blurp.py", line 11, in <module> 
    writeToJSON() 
File "blurp.py", line 9, in writeToJSON 
    outfile.write(unicode(jsonifiedData)) 
ValueError: I/O operation on closed file 
+3

你能显示回溯错误吗? –

+1

在我的Linux上检查了这个,看起来一切正常。 – wanderlust

+0

@wanderlust,hm ...我在macOS上,python 2.7.13,也许这是一个系统的东西......我也会在我的linux机器上试试这个。 – nrebhun

@ rlee827敏锐地和正确地提出了whitespacing问题的可能性。导致违规角色的空白由两个制表符和四个空格组成,这在我的编辑器中是不可见的。用一个标签替换四个空格解决了这个问题。

感谢大家的支持,并感谢@ rlee827解决此问题!

不知道什么是你身边的问题,但我试过同一段代码(蟒蛇3.5),它的工作。

>>> import json 
>>> data = {'thing1' : 'foo', 'thing2' : 'bar'} 
>>> def writeToJSON(): 
     with open('data.json', 'w') as outfile: 
      print (outfile.closed) 
      jsonifiedData = json.dumps(data, indent=4, sort_keys=True, separators=(',', ':'), ensure_ascii=False) 
      outfile.write(str(jsonifiedData)) 
>>> writeToJSON() 
False 
>>> 

和内容data.json的是

{ 
    "thing1":"foo", 
    "thing2":"bar" 
} 
+0

我很感激你为我尝试了这一点。 看起来像@ rlee827是在正确的轨道与whitespacing问题。 – nrebhun