python判斷windows隱藏檔案的方法

來源:互聯網
上載者:User
1. 通過windows attrib 命令擷取檔案隱藏屬性
複製代碼 代碼如下:

Syntax
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/

複製代碼 代碼如下:

import win32file
·
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 win32file
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)

運行結果:

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.