I am trying to open and write to a .txt file, however, I would like to format the name of the file with variable names (that change, so that way I can differentiate the files) in my program.

MY entire code is:

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()

The error I am currently getting is:
file = open("{}_Track_Episode{}.txt", "w").format(track, episode) AttributeError: '_io.TextIOWrapper' object has no attribute 'format'

Some research indicated that I cannot format an object as it is being written to. However, how can I use .format to create files where the name of the file is a dynamic variable in the program?

1 Answers

3
DroidX86 On Best Solutions

You need to format the name of the file before trying to open it.

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

You're getting that error because you're trying to format the object returned by open() (a TextIOWrapper). And that object has no format method