python - 如何在需要使用元素树解析的文件名中使用通配符
问题描述
当我对下面的代码使用通配符时,它会给我一个错误,但是当我使用完整的文件名时它不会。如何在文件名中使用通配符?
import xml.etree.ElementTree as ET
filename = sys.argv[2]
#file name is 'Data*.xml' as in the future it will change every month so need to use a wild card
tree = ET.parse(filename)
root = tree.getroot()
我收到以下错误:
OSError: [Errno 22] 无效参数:'Data*.xml"
解决方案
我通过获取当前目录中的所有文件并检查它是否以字符串开头来解决此问题。
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f.startswith(sys.argv[2]):
filename = f
tree = ET.parse(filename)
必须有一个更简单的方法,我不确定为什么ET.parse
不能处理通配符。
推荐阅读
- swiftui - SwiftUI 的 NavigationView 缺少 Apple Watch 上的后退按钮
- extjs - 如何在按钮单击时路由到视图(ExtJS 6.2)
- javascript - 从 localStorage 中删除记录时从数组中删除元素
- python - 将完整的数据框保存到 txt 文件中
- setuptools - 我试图测试将库升级到 pypi 我只是做了一个非常简单的
- mongodb - MongoDB 聚合 - 如果唯一的最小文档数匹配,则查找
- mysql - 代码是正确的,但我仍然收到语法错误消息
- flutter - 在构建期间获取 Widget 的位置和大小
- android - 如何在使用 Android Hilt 进行仪器测试期间将模拟的 ViewModel 注入 Fragment?
- c++ - int[int*] 如何在 cpp 中工作?它的输出是什么?