【问题标题】:Why do I get an I/O Error?为什么会出现 I/O 错误?
【发布时间】:2014-04-05 00:03:54
【问题描述】:

这是我的代码的一部分,我尝试运行它并在此处的第 12 行收到此错误:ValueError: I/O operation on closed file。但我确信文件“currentRecords”是打开的。怎么了?

c.execute("SELECT * FROM Student, Behaviour")
data = c.fetchall()
currentRecords = open('Current Records - Unsorted', 'w')
l = []
for i in data: #for individual records in the whole database do:
    record = str(i)
    record = record.replace("u'","")
    record = record.replace("'", "")
    record = record.replace("(","") 
    record = record.replace(")", "")
    record = record.replace(","," -")
    currentRecords.write(record+"\r\n")
    currentRecords.write('----------------------------------'+"\r\n")
    currentRecords.close()
    y = open('Current Records - Unsorted','r')
    z = y.read() #opening the file containing the unsorted, formatted records to read
    l.append(z)
    y.close() #z is an array that holds all the records (each record has its own index within l)

【问题讨论】:

  • 您在 for 循环中关闭文件。因此,第一次迭代它是开放的,但从那时起它就关闭了。
  • 代码的用途是什么?对于您想要完成的任务,可能有比在 for-loop 中使用两个文件句柄更清晰的算法
  • 任何依赖于操作 Python 对象的字符串值的代码都应该被视为高度可疑的。
  • 我认为这段代码的最后六行不应该缩进。

标签: python file for-loop input output


【解决方案1】:

Jambofun 解释了原因。这是一种更有效的方法:

c.execute("SELECT * FROM Student, Behaviour")
data = c.fetchall()
currentRecords = open('Current Records - Unsorted', 'w')
dashes = '----------------------------------'
l = []
for i in data: #for individual records in the whole database do:
    record = str(i)
    record = record.replace("u'","")
    record = record.replace("'", "")
    record = record.replace("(","") 
    record = record.replace(")", "")
    record = record.replace(","," -")
    record = "\r\n".join((record, dashes)) + "\r\n"
    currentRecords.write(record)

    l.append(''.join(l))

注意最后一行,我不确定你是否在做你想做的事。您正在累积所有记录。

【讨论】:

    【解决方案2】:

    您似乎想写出用破折号分隔的字段值。让我们来看看正确的方法。

    你需要的代码是:

    record = "\r\n{}\r\n".format("-".join(str(f) for f in row))
    

    这会将每个字段转换为一个字符串(如果它还不是一个),并用破折号连接字符串,然后将其插入到行尾之间。

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 2015-10-19
      • 1970-01-01
      • 2021-02-18
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多