2012-01-30 51 views
1

如何写入函数内的全局文件?Python全局文件

实施例:

output_file=open("output_file_name.txt", "w") 

def write_to_file:  
    global output_file  
    output_file.write('something') 

write_to_file() 

output_file.close() 

上面的代码不工作。它说“ValueError:关闭文件上的I/O操作” 有什么想法?

+2

该代码不会给出该错误。 – 2012-01-30 06:44:12

+0

parens on def? – wim 2012-01-30 06:51:43

+1

适用于Python 2.5,Python 2.7,Python 3.2 – 2012-01-30 09:55:45

回答

2

write_to_file是一个函数,

尝试

def write_to_file(): 

othrwise代码是罚款

2
>>> output_file = "output_file" 
>>> def write_to_file(): 
...  global output_file 
...  with open(output_file,"w") as f: 
...   f.write("I wrote to file") 
...  with open(output_file, "r") as f: 
...   print f.readlines() 
>>> write_to_file() 
    ['I wrote to file'] 

它总是在需要的时候更好地打开一个文件,而不是在开始时开启剧本。
使用with可确保在退出前关闭所有文件处理程序。