【问题标题】:Walking through directory path and opening them with trimesh遍历目录路径并使用 trimesh 打开它们
【发布时间】:2017-11-12 11:52:51
【问题描述】:

我有以下代码:

import os
import trimesh

# Core settings
rootdir = 'path'
extension = ".zip"


for root, dirs, files in os.walk(rootdir):
    if not root.endswith(".zip"):
        for file in files:
            if file.endswith(".stl"):
                mesh = trimesh.load(file)

我收到以下错误:

ValueError: File object passed as string that is not a file!

但是,当我一个一个打开文件时,它可以工作。可能是什么原因?

【问题讨论】:

    标签: python subdirectory trimesh


    【解决方案1】:

    这是因为file文件名,而不是完整的文件路径

    通过使用 os.path.join 和包含目录来解决这个问题:

    mesh = trimesh.load(os.path.join(root,file))
    

    【讨论】:

    • 哦,如果文件夹以“.zip”结尾,我想说跳过,我该怎么做?非常感谢您的回答
    【解决方案2】:

    这不是您问题的直接答案。但是,您可能有兴趣注意到现在这种情况有一个不太复杂的范例。它涉及使用pathlib 模块。

    我不使用trimesh。我将改为处理pdf 文档。

    首先,您可以仅用一行递归地识别目录及其子目录中的所有pdf 文件。

    >>> from pathlib import Path
    >>> for item in path.glob('**/*.pdf'):
    ...     item
    ... 
    WindowsPath('C:/Quantarctica2/Quantarctica-Get_Started.pdf')
    WindowsPath('C:/Quantarctica2/Quantarctica2_GetStarted.pdf')
    WindowsPath('C:/Quantarctica2/Basemap/Terrain/BEDMAP2/tc-7-375-2013.pdf')    WindowsPath('C:/Quantarctica2/Scientific/Glaciology/ALBMAP/1st_ReadMe_ALBMAP_LeBrocq_2010_EarthSystSciData.pdf')
    WindowsPath('C:/Quantarctica2/Scientific/Glaciology/ASAID/Bindschadler2011TC_GroundingLines.pdf')
    
    WindowsPath('C:/Quantarctica2/Software/CIA_WorldFactbook_Antarctica.pdf')
    WindowsPath('C:/Quantarctica2/Software/CIA_WorldFactbook_SouthernOcean.pdf')
    WindowsPath('C:/Quantarctica2/Software/QGIS-2.2-UserGuide-en.pdf')
    

    您会注意到 (a) 完整路径可用,并且 (b) 路径在对象实例中可用。幸运的是,使用str 很容易恢复完整路径。

    >>> import fitz
    >>> for item in path.glob('**/*.pdf'):
    ...     doc = fitz.Document(str(item))
    ... 
    

    这一行表明最终的pdf 文档已作为fitz 文档加载,准备好进行后续处理。

    >>> doc
    fitz.Document('C:\Quantarctica2\Software\QGIS-2.2-UserGuide-en.pdf')
    

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2015-12-30
      • 2023-03-30
      相关资源
      最近更新 更多