Skip to main content
 首页 » 编程设计

python之如果重命名临时文件,如何保留默认 umask

2025年05月04日10lhb25

在 Django 应用程序中,我创建了一个临时文件。此临时文件是使用“0700”权限创建的。但是,我需要在不保留临时文件(0700)权限的情况下重命名该临时文件,但希望该文件获得用户(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") 

请您参考如下方法:

    # 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(tmp_file_path, octal_file_chmod)