1

My html consist of firstname, lastname, age and gender. I am fetching out the values from it and wants to write those value in a file. However i am getting an error of IOError: Bad file descriptor.

On my html page, on submit click i am calling this test.py, which should write data into file name "copy.txt"

My test.py code:

#!/usr/bin/python
import cgi

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("copy","w")
for data in f:
    f.write("Fname")
    f.write("Lname")
    f.write("age")
    f.write("gender")
f.close()

Error:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    for data in f:
IOError: [Errno 9] Bad file descriptor
john john
  • 127
  • 2
  • 6
  • 13

1 Answers1

0

Try the following, its difficult to say what the problem is because you do not provide a traceback:

import cgi

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

with open('copy.txt', 'w') as f:
    for data in f:
        f.write("Fname")
        f.write("Lname")
        f.write("age")
        f.write("gender")

If you cannot use the with keyword, then you are going to have to close it normally:

f = open('copy.txt', 'w')
for data in f:
    f.write("Fname")
    f.write("Lname")
    f.write("age")
    f.write("gender")
f.close()
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199