python判断windows隐藏文件的方法
1. 通过windows attrib 命令获取文件隐藏属性
attrib [ + attribute | - attribute ] [pathname] [/s [/d]]
key
+ : turn an attribute on
- : clear an attribute off
pathname : drive and/or filename e.g. c:\*.txt
/s : search the pathname including all subfolders.
/d : process folders as well
attributes:
r read-only (1)
h hidden (2)
a archive (32)
s system (4)
extended attributes:
e encrypted
c compressed (128:read-only)
i not content-indexed
l symbolic link/junction (64:read-only)
n normal (0: cannot be used for file selection)
o offline
p sparse file
t temporary
2. 隐藏属性值及其含义
constants - the following attribute values are returned by the getfileattributes function:
file_attribute_readonly = 1 (0x1)
file_attribute_hidden = 2 (0x2)
file_attribute_system = 4 (0x4)
file_attribute_directory = 16 (0x10)
file_attribute_archive = 32 (0x20)
file_attribute_normal = 128 (0x80)
file_attribute_temporary = 256 (0x100)
file_attribute_sparse_file = 512 (0x200)
file_attribute_reparse_point = 1024 (0x400)
file_attribute_compressed = 2048 (0x800)
file_attribute_offline = 4096 (0x1000)
file_attribute_not_content_indexed = 8192 (0x2000)
file_attribute_encrypted = 16384 (0x4000)
for example, a file attribute of 0x120 indicates the temporary + archive attributes are set (0x100 + 0x20 = 0x120.)
3. python 通过 win32api 获取文件隐藏属性
python 官网对 win32api 的简单说明 https://www.python.org/download/windows/
下载地址 http://sourceforge.net/projects/pywin32/
·
filenames = [r'd:\test',
r'd:\test\$recycle.bin',
r'd:\test\.file_test.py.swp',
r'd:\test\file_test.py']
for filename in filenames:
print '%4d, %s' %(win32file.getfileattributesw(filename), filename)
运行结果:
4. 与运算(&)更直观判断隐藏文件
示例代码如下,& 运算的结果与隐藏属性值相对应,可以更直观的判断文件类型。
import win32con
filenames = [r'd:\test',
r'd:\test\$recycle.bin',
r'd:\test\.file_test.py.swp',
r'd:\test\file_test.py']
for filename in filenames:
file_flag = win32file.getfileattributesw(filename)
is_hiden = file_flag & win32con.file_attribute_hidden
is_system = file_flag & win32con.file_attribute_system
print '%4d, %s, %s, %s' %(file_flag, is_hiden, is_system, filename)
运行结果: