2016-12-14 26 views
0

我有兩個我正在使用的項目文件,我們稱之爲file.pyprocess.py。有些值在process.py內部傳播,當我想將一個值保存到文件時,(process imports file.py)我從file.py調用一個函數,讓我看到它。如何關閉導入文件中的文件Python

file.py

Open file 
Define file operation functions 
Close file 

注:請注意,我需要明確地打開和關閉文件的原因是因爲我沒有做原始文件的操作,我用sqlite

process.py

import file 
a = data 
call file.function(a) 

的事情是,文件導入完成後關閉。(因爲所有的源代碼運行,也close代碼。)所以我不能運行任何文件讀取/寫入功能process.py

  • 我不也想開和file.py定義的每一個讀/寫功能內關閉文件。

  • 我可以關閉該文件中process.py,而不是file.py,在正確的時間將其關閉 ,但是這種感覺不合適,因爲我覺得 像我必須處理它file.py,因爲process.py本身 無關處理文件。

你建議我做什麼?

+1

這是模糊的,請與實際的代碼更詳細。 – harshil9968

+0

@ harshil9968我認爲我明確提出了這個問題,你能否指出哪些信息是解決問題所必需的? – Rockybilly

回答

0

您可以在file.py中創建一個上下文管理器,它在開始時打開文件並在最後關閉它。然後process.py變成:

import file 
with file.context_manager(): 
    a = data 
    call file.function(a) 

或者你可以把file.py的所有功能放在一個類中。然後在__init__中打開該文件並在__del__中關閉該文件。

0

您可以使用atexit模塊:

file.py

import atexit 

class FileWrapper(object): 

    _file = None 

    @staticmethod 
    def open(filename): 
     if FileWrapper._file and not FileWrapper._file.closed: 
      FileWrapper.close() 
     FileWrapper._file = open(filename) 

    @staticmethod 
    def close(): 
     if FileWrapper._file and not FileWrapper._file.closed: 
      FileWrapper._file.close() 


atexit.register(FileWrapper.close) 

FileWrapper.open("file")