2012-01-30 57 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可確保在退出前關閉所有文件處理程序。