python os.listdir()显示受保护的文件
所以,我正在努力使自己成为一个
Python脚本,它遍历所选的音乐文件夹并告诉用户特定专辑是否没有专辑封面.它基本上遍历所有文件并检查文件[-4:]是否为“(.jpg”,“.bmp”,“.png”),如果为真,则找到一个图片文件.为了说清楚,我的文件夹的结构是:
>音乐文件夹 >北极猴子 > Humbug(2009) >吗啡 >治疗疼痛(1993) .. 等等.我正在测试脚本以查找我的Arctic Monkeys目录中是否有丢失的封面,我的脚本通过“Humbug(2009)”文件夹找到AlbumArtSmall.jpg which doesn’t show up in the command prompt所以我尝试了“显示隐藏文件/文件夹”并仍然没有.然而,the files show up once I uncheck “Hide protected operating system files”,所以这有点奇怪. 我的问题是 – 如何告诉Python跳过搜索隐藏/受保护的文件? 干杯! 编辑 – 所以这是代码: import os def findCover(path,band,album): print os.path.join(path,album) coverFound = False for mFile in os.listdir(os.path.join(path,album)): if mFile[-4:] in (".jpg",".bmp",".png"): print "Cover file found - %s." % mFile coverFound = True return coverFound musicFolder = "E:Music" #for example noCovers = [] for band in os.listdir(musicFolder): #iterate over bands inside the music folder if band[0:] == "Arctic Monkeys": #only Arctic Monkeys print band bandFolder = os.path.join(musicFolder,band) for album in os.listdir(bandFolder): if os.path.isdir(os.path.join(bandFolder,album)): if findCover(musicFolder,album): #if cover found pass #do nothing else: print "Cover not found" noCovers.append(band+" - "+album) #append to list else: #if bandFolder is not actually a folder pass print "" 解决方法
您可以使用
pywin32 module,并手动测试FILE_ATTRIBUTE_HIDDEN或任意数量的属性
FILE_ATTRIBUTE_ARCHIVE = 32 FILE_ATTRIBUTE_ATOMIC_WRITE = 512 FILE_ATTRIBUTE_COMPRESSED = 2048 FILE_ATTRIBUTE_DEVICE = 64 FILE_ATTRIBUTE_DIRECTORY = 16 FILE_ATTRIBUTE_ENCRYPTED = 16384 FILE_ATTRIBUTE_HIDDEN = 2 FILE_ATTRIBUTE_NORMAL = 128 FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192 FILE_ATTRIBUTE_OFFLINE = 4096 FILE_ATTRIBUTE_READONLY = 1 FILE_ATTRIBUTE_REPARSE_POINT = 1024 FILE_ATTRIBUTE_SPARSE_FILE = 512 FILE_ATTRIBUTE_SYSTEM = 4 FILE_ATTRIBUTE_TEMPORARY = 256 FILE_ATTRIBUTE_VIRTUAL = 65536 FILE_ATTRIBUTE_XACTION_WRITE = 1024 像这样: import win32api,win32con #test for a certain type of attribute attribute = win32api.GetFileAttributes(filepath) #The file attributes are bitflags,so you want to see if a given flag is 1. # (AKA if it can fit inside the binary number or not) # 38 in binary is 100110 which means that 2,4 and 32 are 'enabled',so we're checking for that ## Thanks to Nneoneo if attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM): raise Exception("hidden file") #or whatever #or alter them win32api.SetFileAttributes(filepath,win32con.FILE_ATTRIBUTE_NORMAL) #or FILE_ATTRIBUTE_HIDDEN 更改文件后,查看该文件夹,它将不再被隐藏. 发现此信息here和这里:Checking file attributes in python 或者,您可以尝试使用os.stat函数,其文档here然后使用 发现了这些相关问题. (python) meaning of st_mode和How can I get a file’s permission mask? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |