简体   繁体   English

为什么“tree = ElementTree.parse(f)”会在存在 arg 时给出错误“TypeError: parse() missing 1 required positional argument: 'source'”

[英]Why does “tree = ElementTree.parse(f)” give the error “TypeError: parse() missing 1 required positional argument: 'source'” while arg is present

I have a piece of code in a function definition which is:我在函数定义中有一段代码,它是:

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

The string, requests, contains a file path and apparently that file is opened.字符串 requests 包含一个文件路径,显然该文件已打开。 At the beginning of the .py file, I have在 .py 文件的开头,我有

from xml.etree.ElementTree import ElementTree

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:当我在 test.py 中尝试这些行并调用“python3 test.py”时,我没有收到错误消息,但是当我使用 python3 运行程序时,我收到以下错误消息:

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

However as you can see the positional argument of parse() is f.然而,正如你所看到的,parse() 的位置参数是 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:您应该在ElementTree实例上调用parse方法:

eg例如

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

Code fix:代码修复:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:parse() 缺少 1 个必需的位置参数:'timestr' - TypeError: parse() missing 1 required positional argument: 'timestr' Python:Unicode和ElementTree.parse - Python: Unicode and ElementTree.parse 类型错误:udf() 缺少 1 个必需的位置参数:'f' - TypeError: udf() missing 1 required positional argument: 'f' 来自文件的Python ElementTree.parse()不会关闭该文件 - Python ElementTree.parse() from file does not close the file 类型错误:listen() 缺少 1 个必需的位置参数:'source' - TypeError: listen() missing 1 required positional argument: 'source' 使用 ElementTree.parse 解析 XML 文件时出错 - error parsing XML file using ElementTree.parse 类型错误:to_numeric() 缺少 1 个必需的位置参数:'arg' - TypeError: to_numeric() missing 1 required positional argument: 'arg' 尽管存在参数 y,但为什么会出现错误“TypeError: set_window_position() missing 1 required positional argument: 'y'”? - Why error “TypeError: set_window_position() missing 1 required positional argument: 'y'” appears despite the argument y is present? “ TypeError:缺少1个必需的位置参数”实例错误 - “TypeError: missing 1 required positional argument” Instance error Python错误:TypeError:…缺少1个必需的位置参数: - Python ERROR: TypeError: … missing 1 required positional argument:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM