1

ランダムな一連の数学記号 (+、- など) と変数を生成し、それをファイルに書き込み、その後、各数学演算をテストして数学の問題をどれだけうまく解決できるかを確認するプログラムを作成しようとしています -パフォーマンスに基づいてスコアリングし、最大 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
4

1 に答える 1

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ループの反復間で保持されます。

于 2013-10-12T16:10:52.053 に答える