值错误:对关闭的文件执行I/O操作(不应关闭文件)

2024-09-24 10:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个程序,生成一系列随机的数学符号(+,-,等等)和一个变量,然后将其写入一个文件,然后测试每个数学操作,看看它能解决一个数学问题有多好——根据它的性能对它进行评分,然后从中变异出最多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

以及相关的记分文件功能:

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

Tags: andtoinlogforcontentfilewrite
1条回答
网友
1楼 · 发布于 2024-09-24 10:25:49

关闭文件:

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

因此,在循环的下一次迭代中,您传入:

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

f是一个关闭的文件。

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

相关问题 更多 >