2013-10-12 83 views
1

我想創建一個程序,生成一個隨機系列的數學符號(+, - 等)和一個變量,然後寫它然後對每個數學運算進行測試,看看它能夠如何解決數學問題 - 根據其性能對其進行評分,然後根據其性能對5個「子」文件進行變異。ValueError:在關閉的文件上的I/O操作(文件不應該關閉)

當試圖運行下面的代碼,它可以通過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 

Mutat E類功能:

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

關閉文件:

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

相關問題