2 回答

TA貢獻1847條經驗 獲得超11個贊
該文件是否應該僅包含最后計算的值、單次運行的所有值(可能每個都在新行中),或者甚至包含單獨運行的值?然而,這個,有點修改,剪斷可能是你正在尋找的:
if __name__ == '__main__':
with open('try.txt', 'w') as saveFile: # change to 'a' if you want the results to be stored between runs
for e in range(agent.load_episode + 1, EPISODES):
...
for t in range(agent.episode_step):
...
if done:
...
# saveFile.truncate() uncommenting this means that the file only stores the latest value
saveFile.write(str(score) + '\n') # write each result to new line
saveFile.flush() # this line makes the results accessible from file as soon as they are calculated
在 python中,with是打開文件的首選方法,因為它會在適當的時候關閉它。當以 'w' 模式打開文件時,文件內的插入符號被放置在文件的開頭,如果文件中有任何數據,它將被刪除。
'a' 模式附加到文件。你可能想看看這個。
現在我相信您想要不斷地打開和關閉文件,以便在迭代完成后立即訪問數據。這就是 saveFile.flush() 的用途。如果這對您有幫助,請告訴我!
為了更好地控制文件的創建位置,請使用 os 模塊:
import os
directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(directory, 'try.txt')
# print(file_path)
with open(file_path, 'w') as saveFile:
添加回答
舉報