2012-08-29 34 views
2

在Django應用程序上,我創建了一個臨時文件。該臨時文件是使用「0700」權限創建的。但是,我需要重命名臨時文件而不保留臨時文件(0700)的權限,但希望文件獲得用戶的權限(umask)。我不想更改文件的權限。如何在重命名臨時文件時保留默認的umask

這可能嗎?

示例代碼:

import tempfile, os 
content = "hello" 
temp_fd, filename = tempfile.mkstemp(suffix=".tmp", prefix="test1", dir="/tmp") 
with os.fdopen(temp_fd, "wb") as f: 
     f.write(content) 
os.rename(filename,"/home/user/testfile") 

回答

1
# query current umask by replacing it 
    old_umask = os.umask(0) 

    # immediately restore the umask 
    os.umask(old_umask) 

    fd, tmp_file_path = tempfile.mkstemp(prefix='.%s.' % os.path.basename(self._file_path), dir=directory) 

    # calculate the octal chmod and chmod the temp file 
    octal_file_chmod = int('666', 8) - old_umask 
    os.chmod(self._tmp_file_path, octal_file_chmod) 
相關問題