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:
添加回答
举报
