Python 如果重命名临时文件,如何保留默认umask
在Django应用程序上,我创建了一个临时文件。此临时文件是使用“0700”权限创建的。但是,我需要重命名该tempfile而不保留tempfile(0700)的权限,但希望该文件获得用户(umask)的权限。我不想更改文件的权限 这可能吗 示例代码:Python 如果重命名临时文件,如何保留默认umask,python,django,Python,Django,在Django应用程序上,我创建了一个临时文件。此临时文件是使用“0700”权限创建的。但是,我需要重命名该tempfile而不保留tempfile(0700)的权限,但希望该文件获得用户(umask)的权限。我不想更改文件的权限 这可能吗 示例代码: import tempfile, os content = "hello" temp_fd, filename = tempfile.mkstemp(suffix=".tmp", prefix="test1", dir="/tmp") with
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)