这是我的代码的一部分,我尝试运行它并在第12行收到此错误:ValueError:关闭文件的I / O操作。但我确信文件'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)
答案 0 :(得分:1)
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))
注意最后一行,我不确定你是在做你想做的事。您正在积累所有记录。
答案 1 :(得分:1)
您似乎想要写出由短划线分隔的字段值。让我们来看看正确的方法。
您需要的代码是:
record = "\r\n{}\r\n".format("-".join(str(f) for f in row))
这会将每个字段转换为字符串(如果它不是一个字符串),并用短划线连接字符串,然后在行结尾之间插入。