1

从 HTML 中获取值并打印到文件的 Test.py 代码会出现回溯错误 为什么文件描述符的错误正在出现。我是新手。

#!/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()

    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()

回溯错误:

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') + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

我的 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 文件。请检查

4

1 回答 1

1

代码以写入模式 ( ) 打开文件w

您不能迭代以写入模式打开的文件。

如果要将传递的 POST 数据写入文件,只需写入。(没有for循环)。\n如果您希望这些值是行分隔的,请附加换行符 ( )。

f = open("abc.txt","w")
f.write(form.getvalue('firstname', '?') + '\n')
f.write(form.getvalue('lastname', '?') + '\n')
f.write(form.getvalue('age', '?') + '\n')
f.write(form.getvalue('gender', '?') + '\n')
f.close() 

with更优选使用:

with open("abc.txt","w") as f:
    f.write(form.getvalue('firstname', '?') + '\n')
    f.write(form.getvalue('lastname', '?') + '\n')
    f.write(form.getvalue('age', '?') + '\n')
    f.write(form.getvalue('gender', '?') + '\n')

你曾经做过for类似以下的事情吗?

with open("abc.txt", "w") as f:
    for param in ['firstname', 'lastname', 'age', 'gender']:
        f.write(form.getvalue(param, '?') + '\n')
于 2013-10-25T09:22:20.363 回答