Reputation: 127
Test.py code which takes the values from HTML and printing to file gets an traceback error Why the error of file descriptor is comming. I am an newbie.
#!/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()
Tracebacjk Error:
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'
My HTML source file
<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>
Added html file.PLease check
Upvotes: 1
Views: 6004
Reputation: 369294
The code opens the file with write mode (w
).
You cannot iterate the file opened with write mode.
If you want write the passed POST data to file, just write. (without for
loop). Append newline (\n
) if you want the values are line separated.
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()
Using with
is more preferred:
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')
Did you use for
to do something like following?
with open("abc.txt", "w") as f:
for param in ['firstname', 'lastname', 'age', 'gender']:
f.write(form.getvalue(param, '?') + '\n')
Upvotes: 1