python - 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
创建文件名是程序中的动态变量的文件?
解决方案
在尝试打开文件之前,您需要格式化文件名。
file = open("{}_Track_Episode{}.txt".format(track, episode), "w")
您收到该错误是因为您正在尝试(a )format
返回的对象。而那个对象没有方法open()
TextIOWrapper
format
推荐阅读
- java - 如何从 Java 中的异常处理程序中操作类属性?
- javascript - Firebase 谷歌身份验证网络 JS
- reactjs - 有没有办法在 React 开发工具中获取页面上使用的组件的枚举?
- flutter - 如何在颤动中将文本+图标作为步进器的步骤标题
- video - SVT-AV1:编码后的视频搜索在任何视频播放器(甚至 HTML5)中都非常糟糕
- android - Android,Kotlin:我怎样才能只允许我的视图寻呼机在需要时向左滑动
- javascript - 如何在Vue Js中循环遍历Json数组中的子数组?
- python - 芹菜错误 Windows 上无法识别的错误
- c++ - 在 Visual Studio 19 中无法识别 ofstream 和 ifstream 的错误
- python - 如何在 RGB 图像上应用 DCT 隐写术?