python os.listdir() muestra archivos protegidos

So, I'm trying to make myself a Python script which goes through the selected Music folder and tells the user if specific album doesn't have an album cover. It basically goes through all the files and checks if file[-4:] in (".jpg",".bmp",".png"), if true, it found a picture file. Just to make it clear, the structure of my folders is:

  • Carpeta de música
    • Arctic Monkeys
      • Humbug (2009)
      • Suck it and see (2011)
    • Morfina
      • Cure For Pain (1993)

.. and so on. I'm testing the script to find if there's a missing cover in my Arctic Monkeys directory, and my script goes through the "Humbug (2009)" folder and finds AlbumArtSmall.jpg which doesn't show up in the command prompt so I tried "Show hidden files/folders" and still nothing. However, the files show up once I uncheck "Hide protected operating system files", so that's kinda weird.

Mi pregunta es - how do I tell Python to skip searching the hidden/protected files? Revisé el ¿Cómo ignorar los archivos ocultos usando os.listdir ()? but the solution I found there only works for files starting with ".", and that's not what I need.


Edit - so here's the code:

import os

def findCover(path, band, album):
    print os.path.join(path, band, album)
    coverFound = False

    for mFile in os.listdir(os.path.join(path, band, 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, band, album): #if cover found
                    pass                                #do nothing
                    print "Cover not found"
                    noCovers.append(band+" - "+album)   #append to list
            else:                       #if bandFolder is not actually a folder
        print ""

preguntado el 26 de agosto de 12 a las 12:08

A proper answer will depend on how you're walking through your directory, but nevertheless, have you thought about checking the file mode with os.stat? -

I've added the code, hope that helps. Anyway, I tried the os.stat("Folder.jpg"), esto es lo que obtengo: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=34820L, st_atime=1315277420L, st_mtime=1259528972L, st_ctime=1259525728L). I'm not really sure which of the values tells me the file is "protected" or "hidden" for that matter. Hm. -

Doing the os.stat() on an .mp3 file which is visible returns pretty much the same values: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=8379620L, st_atime=1315277422L, st_mtime=1259529036L, st_ctime=1250607460L). -

I might be wrong here, but I think os.stat has no concept of the custom filtering mechanism that windows uses to catalog protected system files. -

@TankorSmash: the link was already given in the first comment, but explicit is better than implicit, eh ? -

1 Respuestas

You can use with the pywin32 módulo, and manually test for FILE_ATTRIBUTE_HIDDEN or any number of attributes

FILE_ATTRIBUTE_ARCHIVE              = 32
FILE_ATTRIBUTE_DEVICE               = 64
FILE_ATTRIBUTE_HIDDEN               = 2
FILE_ATTRIBUTE_NORMAL               = 128
FILE_ATTRIBUTE_OFFLINE              = 4096
FILE_ATTRIBUTE_SYSTEM               = 4
FILE_ATTRIBUTE_VIRTUAL              = 65536

al igual que:

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

After you alter a file, take a look in the folder, it won't be hidden anymore.

Found this information aquí y aquí: Verificando atributos de archivo en Python

Alternativamente, puede intentar utilizar el os.stat function, whose docs aquí y luego usar el stat módulo to further understand what you're looking at.

Found these relevant questions. (python) significado de st_mode y How can I get a file's permission mask?

contestado el 23 de mayo de 17 a las 11:05

Are you positive this reflects what windows considers "protected system files"? I have a feeling that is a custom mechanism. - jdi

@jdi Made a change to check for system hidden files. Hopefully that works for him. I'm not actually sure what the proper name for protected system files are... possibly FILE_ATTRIBUTE_SYSTEM but I haven't tested it out. - TankorSmash

@TankorSmash, man, thanks for all the help, I appreciate it =) At first it didn't work the way it's supposed to. For example, when I ran your code the if condition was False because the values were not equal - attribute = 38 y win32con.FILE_ATTRIBUTE_HIDDEN = 2. Asi que, win32api.GetFileAttributes(HiddenFile) devoluciones 38, while visible files have 32 for a value. Changed the if condition to if attribute == 38 and that's it. Played around with win32api.SetFileAttributes and that works as it's supposed to. Very nice man, thanks for the help, you rock! - E. Normous

Happy to help! I wonder if 38 means that it's SYSTEM = 2, HIDDEN = 4 y ARCHIVE = 32, like some sort of binary encoding or something. - TankorSmash

So, actually, you want if attribute & win32con.FILE_ATTRIBUTE_HIDDEN, since the attributes are bitflags. Also, when you modify the attributes, you must use bit operations to change only the selected attribute, or you risk overwriting some flags you didn't intend to. - neonneo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.