【问题标题】:Why can't my script parse a xml file in a sub directory?为什么我的脚本无法解析子目录中的 xml 文件?
【发布时间】:2019-06-17 12:02:18
【问题描述】:

当我尝试解析子目录中的 xml 文件时,我得到一个 FileNotFoundError。当我将文件放在脚本旁边时,它可以很好地解析它。但为什么呢?

#!/usr/bin/env python3
import os
import xml.etree.ElementTree as ET

script_path = os.path.dirname(os.path.realpath(__file__))

path_to_file = os.path.join(script_path, '/test', 'file.xml')

# works
tree = ET.parse('file.xml')

# Throws file not found error
tree = ET.parse(path_to_file)

【问题讨论】:

  • 从测试中删除 / 并尝试一下

标签: python xml parsing elementtree


【解决方案1】:

通过打印 path_to_file 的值尝试最简单的调试方法。

使用os.path.join(),因此您不必为其构造的路径指定(特定于操作系统的)路径分隔符,这意味着您不需要(不应该)指定它们。

您在test 部分过度指定了路径分隔符 - 更改:

path_to_file = os.path.join(script_path, '/test', 'file.xml')

path_to_file = os.path.join(script_path, 'test', 'file.xml')

【讨论】:

    【解决方案2】:

    尝试写'/test' 不带前导斜线。

    path_to_file = os.path.join(script_path, 'test', 'file.xml')
    

    【讨论】:

      【解决方案3】:

      我自己发布了答案,因为虽然答案解决了问题,但他们没有给出正确的原因,为什么他们的代码有效而我的无效。

      我的代码的一个重要问题是,该行

      path_to_file = os.path.join(script_path, '/test', 'file.xml')
      # Expected value of path_to_file:
      # /path/to/script/test/file.xml
      
      # Output of print(path_to_file):
      # /test/file.xml
      

      包含绝对路径/test,而不是相对路径 ./test或如前所述更好的方式test。 结果是使用/test,生成的路径将不包含script_path 的内容。

      以前的答案可能会在您进入一个目录的情况下有所帮助,但不包括类似的情况

      path_to_file = os.path.join(script_path, 'test/subdir', 'file.xml')
      

      您可能会发现/ 很有用。我认为可以信任os.path.join() 来处理那些特定于平台的目录。如果您不同意我的观点,请告诉我。

      【讨论】:

      • 这不是“以前的答案失败”,而是os.path.join 没有以您感觉“舒适”的方式工作。 /test 是绝对路径。 os.path.join() docs.python.org/3.5/library/os.path.html#os.path.join 的文档说“如果组件是绝对路径,则所有先前的组件都将被丢弃,并从绝对路径组件继续连接”。
      • 感谢您的链接,我正在考虑添加它,它非常清楚地解释了正确的行为。我编辑了我的答案以澄清我的意思。 os.path.join() 确实以我感觉舒适的方式工作,我只需要正确使用它。这是一个明显的错误。
      猜你喜欢
      • 1970-01-01
      • 2010-12-15
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      相关资源
      最近更新 更多