类型错误:open() 需要 0 个位置参数,但给出了 2 个

问题描述 投票:0回答:2

这是代码:

def save():
    f = open('table.html', 'w')
    f.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n")
    f.write("<html xmlns='http://www.w3.org/1999/xhtml'>\n")
    f.write("<head profile='http://gmpg.org/xfn/11'>\n")
    f.write('<title>Table</title>')
    f.write("<style type='text/css'>")
    f.write('body {margin-left:0;margin-right:0;font:normal normal 800 18px Arial;}')
    f.write('a{ text-decoration: }')
    f.write(':link { color: rgb(0, 0, 255) }')
    f.write(':visited {color :rgb(100, 0,100) }')
    f.write(':hover { }')
    f.write(':active { }')
    f.write('table{position: relative; empty-cells: show;border: 1px solid black; border-collapse: collapse}')
    f.write('td{position: relative; border: 1px solid black; text-align: left; padding: 0px 5px 0px 1px}')
    f.write('.tr1{background: #EEFFF9}')
    f.write('.tr2{background: #FFFEEE}')
    f.write('</style>')
    f.write('</head>')
    f.write('<body>')
    f.write('<center>2012 La Jolla Half Marathon</center><br />')
    f.write('<table>')
    f.close()

我得到这个例外:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "C:\Python33\GUICreator1.py", line 11, in save
    f = open('table.html', 'w')
TypeError: open() takes 0 positional arguments but 2 were given

我知道 open 有 2 个参数。 另外,如果我不在函数内运行相同的代码,它会正常运行,不会出现错误。

python python-3.x tkinter
2个回答
6
投票

在模块的其他地方,有一个名为

open()
(定义或导入)的函数,它屏蔽了内置函数。重命名它。

至于你的

save()
函数,你真的应该使用多行字符串,使用三引号,这样可以节省很多
f.write()
调用:

def save():
    with open('table.html', 'w') as f:
        f.write("""\
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n
<html xmlns='http://www.w3.org/1999/xhtml'>\n
<head profile='http://gmpg.org/xfn/11'>\n
<title>Table</title>
<style type='text/css'>
body {margin-left:0;margin-right:0;font:normal normal 800 18px Arial;}
a{ text-decoration: }
:link { color: rgb(0, 0, 255) }
:visited {color :rgb(100, 0,100) }
:hover { }
:active { }
table{position: relative; empty-cells: show;border: 1px solid black; border-collapse: collapse}
td{position: relative; border: 1px solid black; text-align: left; padding: 0px 5px 0px 1px}
.tr1{background: #EEFFF9}
.tr2{background: #FFFEEE}
</style>
</head>
<body>
<center>2012 La Jolla Half Marathon</center><br />
<table>""")

这也使用打开的文件对象作为上下文管理器,这意味着Python将自动为您关闭它。


0
投票

此错误可能还会面临其他问题

  • 看看你的代码中是否有与
    open()
    相同的方法(函数)名称。在这种情况下,只需将您的函数名称更改为与您的程序密切相关的名称即可。
  • 检查
    open()
    之前的代码。 IDE 可能会将其他错误与此相关。
© www.soinside.com 2019 - 2024. All rights reserved.