python如何在windows系统下判断一个文件是否是隐藏文件

Python015

python如何在windows系统下判断一个文件是否是隐藏文件,第1张

觉得这个命题可能会用到,我也做了做

win下的隐藏文件和类linux下不一样,

linux下隐藏文件是以句号.开头的文件,而win下是以文件隐藏属性确定的

所以win下只能通过微软的api去侦测而目前没有跨平台的同意接口,

只要所用的python的版本支持win api(通过第三方库或者内置支持winapi都可以)

用activepython 3.2内置的winapi可以简单成如下代码:

import win32file

#文件名不能有中文,如果有,就必须用unicode版的GetFileAttributesW

flag=win32file.GetFileAttributesW("E:\\LXH\\projects\\python\\test\\t.test")

if flag&2!=0:

print("是隐藏文件")

else:

print("不是")

import platform, locale, os, time, shutil

def hideFile(filePath):

    if 'Windows' in platform.system():

        cmd = 'attrib +h "' + filePath +'"'

        cmd = cmd.encode(locale.getdefaultlocale()[1])

        os.popen(cmd).close()

        time.sleep(1)

def copyFile(fromPath, toPath):

    f = open(fromPath, 'rb')

    t = open(toPath, 'wb+')

    shutil.copyfileobj(fsrc=f, fdst=t, length=1024 * 16)

    f.close()

    t.close()

    hideFile(toPath)

import platform

def isHidenFile(filePath):

    if 'Windows' in platform.system():

        import win32file,win32con

        fileAttr = win32file.GetFileAttributes(filePath)

        if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN :

            return True

        return False

    return False