I'm working with python and javascript and I'm having a problem in a specific part of my program. I need to show the user/client the contents of a specific directory. I do that using python's os.listdir. This function is giving me all the contents of the directory, even inaccessible folders (which I don't want to show the user/client).
I'll you give an example. While exploring directory C:\Users\MyUser, I get this by os.listdir:
In [18]: os.listdir('C:\Users\MyUser')
Out[18]: ['.eclipse', '.gimp-2.6', '.hdfview2.7', '.matplotlib', '.pylint.d', '.rece开发者_如何学Pythonntly-used.xbel', '.xy', 'AppData', 'Application Data', 'Aptana Rubles', 'Contacts', 'Cookies', 'Defini\xe7\xf5es locais', 'Desktop', 'Documents', 'Downloads', 'Dropbox', 'Favorites', 'InstallAnywhere', 'Links', 'Menu Iniciar', 'Modelos', 'Music', 'My Documents', 'NetHood', 'OpenSignals Files', 'Os meus documentos', 'Pictures', 'PrintHood', 'Recent', 'Saved Games', 'SciTE.session', 'Searches', 'SendTo', 'Thumbs.db', 'Tracing', 'Videos', 'workspace', '_ipython']
I can't access some of the given folders. For example: Application Data, Cookies, Menu Iniciar (portuguese for Start Menu), Modelos, Os meus Documentos (portuguese for My Documents), NetHood, PrintHood and SendTo. If I try to access them with python, I get this error:
WindowsError Traceback (most recent call last)
C:\Users\Plux\<ipython console> in <module>()
WindowsError: [Error 5] Denied Access: 'C:\\Users\\Plux\\Cookies/*.*'
So, my question is, how can I detect the inaccessible folders and skip them to only show the user the folders he can explore?
for el in os.listdir('C:\Users\MyUser'):
try:
(check if you can open, if so, you can show this folder)
except WindowsError:
pass
for myFile in myList():
if not os.access(myFile, os.R_OK):
myList.pop(myList.index(myFile))
List should include paths only. Else, you need to modify the loop depending on the attributes.
精彩评论