【问题标题】:How do i write html data into file in python, Error is "IOError: [Errno 9] Bad file descriptor" [duplicate]我如何在python中将html数据写入文件,错误是“IOError:[Errno 9] Bad file descriptor” [重复]
【发布时间】:2023-03-31 05:15:01
【问题描述】:

我的 html 由名字、姓氏、年龄和性别组成。我正在从中取出值并希望将这些值写入文件中。但是我收到 IOError: Bad file descriptor 的错误。

在我的 html 页面上,点击提交时,我调用了这个 test.py,它应该将数据写入文件名“copy.txt”

我的 test.py 代码:

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

错误:

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

【问题讨论】:

  • 你必须使用f = open("copy.txt","w")
  • @GamesBrainiac:在上述链接中找不到解决方案
  • @GamesBrainiac:你能租用帮助吗?我不明白上面的链接

标签: python html cgi


【解决方案1】:

尝试以下,很难说是什么问题,因为你没有提供回溯:

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

如果你不能使用with关键字,那么你将不得不正常关闭它:

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

【讨论】:

  • 我不能使用 'with' 关键字。它在 python 2.6 中保留
  • 还更新了回溯错误
  • @johnjohn 看看更新,这是重复的。
  • 还是同样的错误:Bad File Descriptor......我应该把我的html代码也放上>??
猜你喜欢
  • 2016-04-15
  • 2021-12-05
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2013-06-16
相关资源
最近更新 更多