如何使用python的os.listdir跳过无法访问的文件夹? [英] How to skip the inaccessible folders with python's os.listdir?

查看:1409
本文介绍了如何使用python的os.listdir跳过无法访问的文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python和javascript,我在程序的某个特定部分遇到问题。我需要向用户/客户端显示特定目录的内容。我使用python的os.listdir做到这一点。这个功能给了我所有目录的内容,甚至是不可访问的文件夹(我不想显示用户/客户端)。

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).

我会举个例子。在浏览目录C:\Users\MyUser时,我得到这个os.listdir:

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',  '.recently-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无法访问某些给定的文件夹。例如:应用程序数据,Cookie,菜单菜单(开始菜单的葡萄牙语),Modelos,Os meus Documentos(我的文档的葡萄牙语),NetHood,PrintHood和SendTo。如果我尝试使用python访问它,我得到这个错误:

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/*.*'

所以,我的问题是,我如何检测到不可访问的文件夹,并跳过它们,只向用户显示他的文件夹可以在os.listdir('C:\Users)中探索?

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  

这篇关于如何使用python的os.listdir跳过无法访问的文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆