如何使用 os.listdir() 忽略隐藏文件?

发布于 2024-11-30 06:27:57 字数 256 浏览 8 评论 0原文

我的 python 脚本执行一个 os.listdir(path) ,其中路径是一个队列,其中包含我需要一一处理的档案。

问题是我在数组中获取列表,然后只执行一个简单的 array.pop(0) 。在我将项目置于 subversion 之前,它工作得很好。现在我在数组中得到了 .svn 文件夹,当然它会使我的应用程序崩溃。

所以这是我的问题:是否有一个函数可以在执行 os.listdir() 时忽略隐藏文件,如果没有,最好的方法是什么?

My python script executes an os.listdir(path) where the path is a queue containing archives that I need to treat one by one.

The problem is that I'm getting the list in an array and then I just do a simple array.pop(0). It was working fine until I put the project in subversion. Now I get the .svn folder in my array and of course it makes my application crash.

So here is my question: is there a function that ignores hidden files when executing an os.listdir() and if not what would be the best way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

千纸鹤带着心事 2024-12-07 06:27:57

您可以自己编写一个:

import os

def listdir_nohidden(path):
    for f in os.listdir(path):
        if not f.startswith('.'):
            yield f

或者您可以使用 glob

import glob
import os

def listdir_nohidden(path):
    return glob.glob(os.path.join(path, '*'))

其中任何一个都会忽略所有文件名以 '.' 开头。

You can write one yourself:

import os

def listdir_nohidden(path):
    for f in os.listdir(path):
        if not f.startswith('.'):
            yield f

Or you can use a glob:

import glob
import os

def listdir_nohidden(path):
    return glob.glob(os.path.join(path, '*'))

Either of these will ignore all filenames beginning with '.'.

白馒头 2024-12-07 06:27:57

这是一个老问题,但似乎缺少使用列表理解的明显答案,因此我将其添加到此处以确保完整性:

[f for f in os.listdir(path) if not f.startswith('.')]

作为旁注,文档状态 listdir 将返回结果“任意顺序”,但常见的用例是按字母顺序排序。如果您希望目录内容按字母顺序排序而不考虑大小写,您可以使用:(

sorted((f for f in os.listdir() if not f.startswith(".")), key=str.lower)

编辑为使用 key=str.lower 而不是 lambda

This is an old question, but seems like it is missing the obvious answer of using list comprehension, so I'm adding it here for completeness:

[f for f in os.listdir(path) if not f.startswith('.')]

As a side note, the docs state listdir will return results in 'arbitrary order' but a common use case is to have them sorted alphabetically. If you want the directory contents alphabetically sorted without regards to capitalization, you can use:

sorted((f for f in os.listdir() if not f.startswith(".")), key=str.lower)

(Edited to use key=str.lower instead of a lambda)

抱着落日 2024-12-07 06:27:57

在 Windows、Linux 和 OS X 上:

if os.name == 'nt':
    import win32api, win32con


def folder_is_hidden(p):
    if os.name== 'nt':
        attribute = win32api.GetFileAttributes(p)
        return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
    else:
        return p.startswith('.') #linux-osx

On Windows, Linux and OS X:

if os.name == 'nt':
    import win32api, win32con


def folder_is_hidden(p):
    if os.name== 'nt':
        attribute = win32api.GetFileAttributes(p)
        return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
    else:
        return p.startswith('.') #linux-osx
糖粟与秋泊 2024-12-07 06:27:57

Joshmaker 对您的问题有正确的解决方案。
如何使用 os.listdir() 忽略隐藏文件?

然而,在Python 3中,建议使用pathlib而不是os.pathlib。

from pathlib import Path 
visible_files = [
    file for file in Path(".").iterdir() if not file.name.startswith(".")
]

Joshmaker has the right solution to your question.
How to ignore hidden files using os.listdir()?

In Python 3 however, it is recommended to use pathlib instead of os.

from pathlib import Path 
visible_files = [
    file for file in Path(".").iterdir() if not file.name.startswith(".")
]
江南烟雨〆相思醉 2024-12-07 06:27:57

glob:(

>>> import glob
>>> glob.glob('*')

glob 声称使用 listdirfnmatch 在底层,但它也会检查前导 '.',而不是使用 fnmatch。)

glob:

>>> import glob
>>> glob.glob('*')

(glob claims to use listdir and fnmatch under the hood, but it also checks for a leading '.', not by using fnmatch.)

゛时过境迁 2024-12-07 06:27:57

我认为循环遍历所有项目的工作量太大。我更喜欢这样简单的东西:

lst = os.listdir(path)
if '.DS_Store' in lst:
    lst.remove('.DS_Store')

如果目录包含多个隐藏文件,那么这会有所帮助:

all_files = os.popen('ls -1').read()
lst = all_files.split('\n')

对于平台独立性,正如 @Josh 提到的,glob 效果很好:

import glob
glob.glob('*')

I think it is too much of work to go through all of the items in a loop. I would prefer something simpler like this:

lst = os.listdir(path)
if '.DS_Store' in lst:
    lst.remove('.DS_Store')

If the directory contains more than one hidden files, then this can help:

all_files = os.popen('ls -1').read()
lst = all_files.split('\n')

for platform independence as @Josh mentioned the glob works well:

import glob
glob.glob('*')
念﹏祤嫣 2024-12-07 06:27:57
filenames = (f.name for f in os.scandir() if not f.name.startswith('.'))
filenames = (f.name for f in os.scandir() if not f.name.startswith('.'))
薔薇婲 2024-12-07 06:27:57

您只需使用一个简单的 for 循环即可排除任何包含“.”的文件或目录。

专业人士代码:

import os

directory_things = [i for i in os.listdir() if i[0] != "."] # Exclude all with . in the start

菜鸟代码

items_in_directory = os.listdir()
final_items_in_directory = []

for i in items_in_directory:
    if i[0] != ".": # If the item doesn't have any '.' in the start
        final_items_in_directory.append(i)

You can just use a simple for loop that will exclude any file or directory that has "." in the front.

Code for professionals:

import os

directory_things = [i for i in os.listdir() if i[0] != "."] # Exclude all with . in the start

Code for noobs

items_in_directory = os.listdir()
final_items_in_directory = []

for i in items_in_directory:
    if i[0] != ".": # If the item doesn't have any '.' in the start
        final_items_in_directory.append(i)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文