문제

This is part of my code, I try running it and receive this error on line 12 here:ValueError: I/O operation on closed file. But I am sure that the file, 'currentRecords' is open. What is wrong?

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)

올바른 솔루션이 없습니다

다른 팁

Jambofun has explained why. Here is a more efficient way of doing it:

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

Note the last line, I am not sure you are doing what you want to do. You are accumulating all the records to the moment.

You appear to want to write out the field values separated by dashes. Let's take a look at the right way to do that.

The code you need is:

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

This converts each field to a string (if it isn't already one) and joins up the strings with dashes then inserts that between the line endings.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top