我正在尝试打开并写入.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
创建文件?
答案 0 :(得分:3)
您需要先打开文件的格式,然后再尝试打开文件。
file = open("{}_Track_Episode{}.txt".format(track, episode), "w")
由于尝试format
(一个open()
)返回的对象而TextIOWrapper
时出现了该错误。而且该对象没有format
方法