python - 在mac中查找特定类型的文件(python)

标签 python macos

我有一个脚本可以编译几个程序并将输出放入一个文件夹中,我的脚本中有一个函数可以迭代并查找文件夹中的所有可执行文件并将它们添加到列表中,

def _oswalkthrough(direc,filelist=[]):
    dirList=os.listdir(direc)
    for item in dirList:
        filepath = direc+os.sep+item
        if os.path.isdir(filepath):
            filelist = _oswalkthrough(filepath,filelist)
        else:
            if ".exe" == item[-4:]:
                filelist.append(filepath)
    return filelist

这在Windows上没有任何问题,但是当我在Mac上运行它时,我无法让它工作,当然Mac中编译的文件不会以“.exe”结尾,所以如果语句没有用,所以我创建了一个包含编译文件名称的列表,并将脚本更改为以下内容,但仍然没有结果,它添加了所有文件,包括“.o”文件,这是我不想要的! 。我只想要exe? (我不知道它们在 mac 中叫什么!)。

def _oswalkthrough(direc,filelist=[]):
    dirList=os.listdir(direc)
    for item in dirList:
        filepath = direc+os.sep+item
        if os.path.isdir(filepath):
            filelist = _oswalkthrough(filepath,filelist)
        else:
            for file in def_scons_exe:
                if file == item[-4:]:
                    filelist.append(filepath)
    return filelist

最佳答案

首先,您的代码在 Mac 上不起作用,因为例如您的条件 if file == item[-4:] 不适用于 .o (它们的长度不同,它们永远不会相等)。

另一件事,看看os.walk函数(它会在你的路径遍历中节省一些空间)。

另一个问题是检查扩展名并不能保证文件是可执行的。您最好使用 os.access 来检查文件访问模式,在您的情况下(您想知道它是否可执行),您必须检查 os.X_OK 标志。这是用于检查的代码片段:

import os

if os.access("/path/to/file.o", os.X_OK):
    print 'Executable!'

关于python - 在mac中查找特定类型的文件(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11987356/

相关文章:

python - 从列表 os 文件路径构建树 (Python) - 性能依赖

python - 选择 numpy 数组,使最后一个元素为 1

objective-c - Cocoa Mac,IB - 能否使 NSButton( radio 类型)的行为类似于类型 "Switch",同时在点击开/关方面保持边框 "Radio"

c++ - 是否可以在 Mac OSX 10.6 中静态链接 libstdc++?

c - Mac OS X 上的标准 C 库在哪里?

linux - 如何使用每个 screen 的自定义命令启动多个 screen ?

python - 图片的 urlretrieve 返回 HTTP 错误 403 : Forbidden

python - Pandas 获得每个组的多次首次出现

python - 删除包含数组中内容的 pandas DataFrame 行

适用于 PostgreSQL 的 Excel 2016 和 ODBC 驱动程序