[英]Why can't my script parse a xml file in a sub directory?
When I try to parse a xml file in a sub directory I get a FileNotFoundError
. 当我尝试解析子目录中的xml文件时,出现
FileNotFoundError
。 When I put the file next to the script it can parse it fine. 当我将文件放在脚本旁边时,它可以很好地解析。 But why?
但为什么?
#!/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)
Try the easiest possible way of debugging by printing the value of path_to_file. 通过打印path_to_file的值,尝试最简单的调试方法。
os.path.join()
is used so you don't have to specify the (os-specific) path separator character for the path it constructs, which means you don't need to (shouldn't) specify them. os.path.join()
,因此您不必为其构造的路径指定(特定于OS的)路径分隔符,这意味着您无需(不应)指定它们。
You are over-specifying the path separator on the test
part - change: 您在
test
零件上过度指定了路径分隔符-更改:
path_to_file = os.path.join(script_path, '/test', 'file.xml')
to 至
path_to_file = os.path.join(script_path, 'test', 'file.xml')
尝试写'/test'
不要加斜杠。
path_to_file = os.path.join(script_path, 'test', 'file.xml')
I am posting the answer myself because although the answers solve the problem, they do not give the correct reason why their code works and mine doesn't. 我自己发布答案,因为尽管答案可以解决问题,但它们并没有给出代码有效而我的代码无效的正确原因。
The significant issue with my code is, that the line 我的代码的重要问题是,该行
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
contains the absolute path /test
instead of the relative path ./test
or as pointed out earlier the better way test
. 包含绝对路径
/test
而不是相对路径 ./test
或者如先前指出的更好的方法test
。 The result is that with /test
, the resulting path will not contain the contents of script_path
. 结果是,使用
/test
,结果路径将不包含script_path
的内容。
The previous answers might help in cases where you go down one directory, but don't cover cases like 在您进入一个目录的情况下,先前的答案可能会有所帮助,但不会涵盖以下情况
path_to_file = os.path.join(script_path, 'test/subdir', 'file.xml')
Where you might find the /
useful. 您可能会发现
/
有用的地方。 I think one can trust os.path.join()
to take care of those platform specific directories. 我认为可以相信
os.path.join()
来照顾那些平台特定的目录。 Please let me know if you don't agree with me one this. 如果您不同意我的一项,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.