首页 > 解决方案 > Python 3 - 问题格式化正在写入的文件

问题描述

我正在尝试打开并写入 .txt 文件,但是,我想在我的程序中使用变量名(更改,以便我可以区分文件)格式化文件名。

我的整个代码是:

def main():
    num_episodes = 50
    steps = 10000
    learning_rate_lower_limit = 0.02
    learning_rate_array = numpy.linspace(1.0, learning_rate_lower_limit, num_episodes)
    gamma = 1.0
    epsilon = .25
    file = csv_to_array(sys.argv[1])
    grid = build_racetrack(file)
    scenario = sys.argv[2]
    track = sys.argv[3]

    if(track == "right"):
        start_state = State(grid=grid, car_pos=[26, 3])
    else:
        start_state = State(grid=grid, car_pos=[8,1])

    move_array = []
    for episode in range(num_episodes):
        state = start_state
        learning_rate = learning_rate_array[episode]

        total_steps = 0
        for step in range(steps):
            total_steps = total_steps + 1
            action = choose_action(state, epsilon)
            next_state, reward, finished, moves = move_car(state, action, scenario)
            move_array.append(moves)
            if (finished == True):
                print("Current Episode: ", episode, "Current Step: ", total_steps)
                file = open("{}_Track_Episode{}.txt", "w").format(track, episode)
                file.write(str(move_array))
                move_array = []
                break
            else:
                query_q_table(state)[action] = query_q_table(state, action) + learning_rate * (
                            reward + gamma * numpy.max(query_q_table(next_state)) - query_q_table(state, action))
                state = next_state
main()

我目前得到的错误是:
file = open("{}_Track_Episode{}.txt", "w").format(track, episode) AttributeError: '_io.TextIOWrapper' object has no attribute 'format'

一些研究表明,我无法在写入对象时对其进行格式化。但是,我如何使用.format创建文件名是程序中的动态变量的文件?

标签: pythonpython-3.x

解决方案


在尝试打开文件之前,您需要格式化文件名。

file = open("{}_Track_Episode{}.txt".format(track, episode), "w")

您收到该错误是因为您正在尝试(a )format返回的对象。而那个对象没有方法open()TextIOWrapperformat


推荐阅读