2011-11-22 77 views

回答

7

這不是你所需的東西,因爲它只是測試一個給定的文件是否是可寫的。但如果它是有幫助的:

import os 

filename = "a.txt" 
if not os.access(filename, os.W_OK): 
    print "Write access not permitted on %s" % filename 

(我不知道有任何獨立於平臺的方式做你問什麼)

+1

謝謝!但似乎os.access只檢查文件的可讀性/可寫性,但我想檢查文件是否已經打開或不打開。感謝您的進一步建議。 –

0

我不認爲有一個簡單的方法做你想要什麼,但一開始可能是重新定義open()並添加自己的管理代碼。那就是說,你爲什麼想這樣做?

1

下面是一個使用ctypes的用於Windows的解決方案IS_OPEN:

from ctypes import cdll 

_sopen = cdll.msvcrt._sopen 
_close = cdll.msvcrt._close 
_SH_DENYRW = 0x10 

def is_open(filename): 
    if not os.access(filename, os.F_OK): 
     return False # file doesn't exist 
    h = _sopen(filename, 0, _SH_DENYRW, 0) 
    if h == 3: 
     _close(h) 
     return False # file is not opened by anyone else 
    return True # file is already open