ValueError:关闭文件的I / O操作(不应关闭文件)

时间:2013-10-12 16:07:05

标签: python file python-3.x while-loop

我正在尝试创建一个程序,生成一系列随机数学符号(+, - 等)和一个变量,然后将其写入文件,然后测试每个数学运算,看看它能如何解决数学问题 - 根据它的表现进行评分,然后从中变异5个'子'文件。

当尝试运行以下代码时,它可以在第一次运行while循环时运行良好,但每次运行后它都无效并抛出此错误:

Traceback (most recent call last):
  File "C:\Python Files\Evolving\mEvolve.py", line 97, in <module>
    sList.append(scoreFile(f, lFile))
  File "C:\Python Files\Evolving\mEvolve.py", line 22, in scoreFile
    file.seek(0)
ValueError: I/O operation on closed file

这是我试图运行的代码:

# Main code
lFile = open('eLog.txt', mode='w') # Log file for logging events
bFile = open('ops.txt', mode='w+') # Starting 'parent' file to modify
lFile.write("Started evolution. New file 'ops.txt' created.")
r = pseudoRandom(1, 5) 
for i in range(r): # Write a random amount of data to file
    bFile.write(genAtom())
lFile.write("\nWrote %d characters into file 'ops.txt' to start." % r)

while True:
    sList = [] # Empty the temporary score list
    for i in range(pseudoRandom(1, 5)): # Generate between 1 and 5 'mutated' files.
        genCount = genCount + 1
        bFile.seek(0)
        fContent = list(bFile.read()) # Get parent file content
        nContent = mutate(fContent, lFile, pseudoRandom(1, 5)) # Mutate file content
        fName = "ops[%d].txt" % genCount
        nFile = open(fName, mode='w+') # Open new 'child' file
        nFile.write(''.join(nContent)) # and write mutated content to it
        fList.append(nFile)
    bFile.close() # Close old parent file
    remove(bFile.name) # and remove it
    for f in fList: # Score all child files
        sList.append(scoreFile(f, lFile)) # <-- Error occurs here
    bFile = fList[sList.index(min(sList))] # Choose new best file based on scores
    lFile.write("\nScored %d files. Best score %d." % (len(sList), min(sList)))
    scoreList.append(min(sList))
    del fList[sList.index(min(sList))] # Remove best scoring child file from fList
    for f in fList: # and delete all other child files
        f.close()
        remove(f.name)
    c = input("Finished, loop again? (Leave blank for yes or n for no): ")
    if c.lower() == 'n':
        break

和相关的scoreFile函数:

def scoreFile(file, log): # Score provided file
    optPos = 0
    curPos = 10
    s = 1
    file.seek(0)
    fileList = list(file.read())
    fileRes = ' '.join(str(e) for e in fileList) # Translate file data
    try: # and test to see if its contents can solve a problem
        scr = abs(optPos-eval("curPos = curPos %s" % fileRes))
    except: # Give it terrible score if it doesn't make sense
        scr = 1000
    log.write("\nFile '%s' scored %d." % (file.name, scr))
    return scr

变异功能:

def mutate(fileCont, log, lCount): # Mutate the file provided
    for i in range(lCount): # a certain amount of times
        try:
            actionLoc = pseudoRandom(0, len(fileCont)-1) # Pick a random part of file content to mess with
        except: # File content was under two characters (results in asking for between 0 and 0)
            actionLoc = 0 # so just set it to 0
        action = pseudoRandom(0, 2)
        if action == 0: # Replace
            newItem = genAtom() # Generate new 'atom' of code to replace with
            try:
                fileCont[actionLoc] = newItem
                log.write("\nMutated: Replaced atom %d." % actionLoc)
            except: # Chosen content doesn't exist (file was likely empty)
                fileCont.insert(actionLoc, newItem)
                log.write("\nMutated: Attempted atom replacement failed;")
                log.write("\ninserted new random atom instead for atom %d." % actionLoc)
        elif action == 1: # Delete
            try:
                del fileCont[actionLoc]
                log.write("\nMutated: Deleted atom %d." % actionLoc)
            except: # Chosen content doesn't exist (file was likely empty)
                newItem = genAtom()
                fileCont.insert(actionLoc, newItem)
                log.write("\nMutated: Attempted atom deletion failed;")
                log.write("\ninserted new random atom instead for atom %d." % actionLoc)
        else: # Duplicate
            try: # Take the content and insert a duplicate
                newItem = fileCont[actionLoc]
                fileCont.insert(actionLoc, newItem)
                log.write("\nMutated: Duplicated atom %d." % actionLoc)
            except: # Chosen content doesn't exist (file was likely empty)
                newItem = genAtom()
                fileCont.insert(actionLoc, newItem)
                log.write("\nMutated: Attempted atom duplication failed;")
                log.write("\ninserted new random atom instead for atom %d." % actionLoc)
    return fileCont

1 个答案:

答案 0 :(得分:1)

执行关闭文件:

for f in fList: # and delete all other child files
    f.close()
    remove(f.name)

所以在你传递的while循环的下一次迭代中:

for f in fList: # Score all child files
    sList.append(scoreFile(f, lFile))

f是一个已关闭的文件。

remove(f.name) fList删除文件对象。您清除sList,但在循环迭代之间保留fList