在 *nix 中,我可以简单地添加一个 .
到一个文件以使其“隐藏”。还有一些方法可以使文件在 Windows 中隐藏。
有没有办法在 python 中使文件隐藏跨平台?
目前:
def write_hidden(file_name, data):
file_name = '.' + file_name
with open(file_name_, 'w') as f:
f.write(data)
但正如我所说,这只适用于 *nix 系统。
最佳答案
你可以这样做:
import os
import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
def write_hidden(file_name, data):
"""
Cross platform hidden file writer.
"""
# For *nix add a '.' prefix.
prefix = '.' if os.name != 'nt' else ''
file_name = prefix + file_name
# Write file.
with open(file_name, 'w') as f:
f.write(data)
# For windows set file attribute.
if os.name == 'nt':
ret = ctypes.windll.kernel32.SetFileAttributesW(file_name,
FILE_ATTRIBUTE_HIDDEN)
if not ret: # There was an error.
raise ctypes.WinError()
这尚未经过测试,但应该可以正常工作。
您还可能希望看到帮助我实现此目的的其他问题:
关于Python跨平台隐藏文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25432139/