繁体   English   中英

TypeError:open()接受0个位置参数,但给出了2个

[英]TypeError: open() takes 0 positional arguments but 2 were given

这是代码:

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个参数。 另外,如果我不在函数中运行相同的代码,则它可以正常运行且没有错误。

在模块的其他位置,您有一个名为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会自动为您关闭它。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM