为什么"tree = ElementTree.parse(f)"为何?给出错误"TypeError:parse()缺少1个必需的位置参数:'source'";当arg存在时 [英] Why does "tree = ElementTree.parse(f)" give the error "TypeError: parse() missing 1 required positional argument: 'source'" while arg is present

查看:92
本文介绍了为什么"tree = ElementTree.parse(f)"为何?给出错误"TypeError:parse()缺少1个必需的位置参数:'source'";当arg存在时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数定义中有一段代码:

I have a piece of code in a function definition which is:

    try:
        with open(requests,'rt') as f:
            tree = ElementTree.parse(f)

该字符串请求包含一个文件路径,并且显然该文件已打开.在.py文件的开头,我有

The string, requests, contains a file path and apparently that file is opened. At the beginning of the .py file, I have

from xml.etree.ElementTree import ElementTree

当我在test.py中尝试这些行并调用"python3 test.py"时,我没有收到错误消息,但是当我使用python3运行程序时,出现以下错误消息:

When I try these lines in test.py and call "python3 test.py" I do NOT get an error message, however when I run the program with python3 I get the following error message:

    tree = ElementTree.parse(f)
TypeError: parse() missing 1 required positional argument: 'source'

但是您可以看到parse()的位置参数是f.我确实使用了一条打印命令来检查请求的值,并显示正确的文件名.

However as you can see the positional argument of parse() is f. I did put a print command to examine the value of requests, and it showed the proper file name.

推荐答案

您应调用

You should invoke the parse method on an ElementTree instance:

例如

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("index.xhtml")

代码修复:

try:
        with open(requests,'rt') as f:
            tree = ElementTree()
            tree.parse(f)

这篇关于为什么"tree = ElementTree.parse(f)"为何?给出错误"TypeError:parse()缺少1个必需的位置参数:'source'";当arg存在时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆