我正在从HTML文件中获取值,但是遇到了TracebackError错误:我不知道应该怎么改变?
Traceback (most recent call last):
File "test.py", line 33, in <module>
get_data()
File "test.py", line 25, in get_data
f.write(form.getvalue('firstname'))
TypeError: argument 1 must be string or read-only character buffer, not None
我的Python代码:
# !/usr/bin/python
import cgi
def get_data():
'''
This function writes the HTML data into the file
'''
print "Content- type : text/html\n"
form = cgi.FieldStorage()
#Fname = form.getvalue('firstname')
#Lname = form.getvalue('lastname')
#Age = form.getvalue('age')
#Gender = form.getvalue('gender')
f = open("abc.txt","w")
f.write(form.getvalue('firstname'))
f.write(form.getvalue('lastname'))
f.write(form.getvalue('age'))
f.write(form.getvalue('gender'))
f.close()
#print "Hello ", Fname, Lname, Age, Gender
get_data()
我是一名新手,无法找到错误。请帮我解决。
HTML文件:
<html>
<head>
<title>INFORMATION</title>
</head>
<body>
<form action = "/cgi-bin/test.py" method = "post">
FirstName:
<input type = "text" name = "firstname" /><br>
LastName:
<input type = "text" name = "lastname" /><br>
Age:
<input type = "text" name = "age" /><br>
Gender:
<input type="radio" name="gender" value="male" /> Male
<input type="radio" name="gender" value="female" /> Female
<input type = "submit" name = "submit "value = "SUBMIT">
<input type = "reset" name = "reset" value = "RESET">
</form>
</body>
</html>
with
语句来处理文件。 - Gareth Lattywith
。 - Games Brainiacform.getvalue('firstname')
是None
。很可能是没有从FieldStorage
中获取到值。 - thefourtheyewith
和上下文管理器在2.5中被添加,如果你使用from __future__ import with_statement
,而在2.6中则默认可用。 - Gareth Latty