在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")
答案 0 :(得分: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)
答案 1 :(得分:0)
shutil.move
应该保留权限,但我不确定它是如何实现的,也许您必须使用shutil.copy2
和os.remove
的组合。