Python修改ini游戏存档报TypeError: write()参数需为str而非tuple
问题现象
开发.ini格式游戏存档编辑工具时,程序运行触发类型错误,报错信息为write() argument must be str, not tuple,报错触发点为写回存档的save.writelines(lines)语句。
程序核心逻辑:通过tkinter组件引导用户选择游戏目录,读取目录下save_data_main.ini存档的全部内容,提示用户输入新的room数值后修改存档第6行(Python列表索引为5)的对应内容,再将修改后的内容写回文件,写回操作执行时触发上述报错。
核心问题代码如下:
from tkinter import * from tkinter import filedialog from pathlib import Path # All important variables here to simplify reading my code directory = None path = None save = None room = None def main(): print("\n[#] Select your game directory") tk = Tk() tk.geometry("0x0") tk.wm_attributes('-toolwindow', 'True') global directory directory = filedialog.askdirectory(title="Select the game directory...") path = Path(f"{directory}/save_data_main.ini") if path.is_file(): # If save file exist save = open(path, 'r+') lines = save.readlines() save.close() print("\n[*] Your currently at the", lines[5]) print("[!] Please choose a number superior than 0 and inferior than 1000!") room = input("[#] Change the room value : ") lines[5] = "room=", str(room) save = open(path, 'w+') save.writelines(lines) save.close() print("[*] Value changed with success.") else: # Error save file doesnt exist print("\n[!] ERROR: Save file doesn't exist! Try to create a new Game.") input("[*] Press Enter to continue...") exit() if __name__ == '__main__': main()
报错根因
错误出在修改第6行内容的赋值语句:
lines[5] = "room=", str(room)
Python里如果赋值语句右侧用逗号分隔多个值,解释器会自动把这几个值打包成元组(tuple),而不是执行字符串拼接。writelines()方法要求传入的列表里所有元素都必须是字符串类型,当程序遍历到你替换进去的元组元素尝试写入文件时,就会抛出argument must be str, not tuple的类型错误。
另外原修改逻辑没有保留行尾的换行符\n,就算修完类型错误,写回文件后也会出现第6行和第7行内容粘在一起的格式问题。
修复方案
把原来的元组赋值改成字符串拼接,同时补上行尾的换行符即可,两种写法都能实现:
- 用f-string拼接(写法更简洁):
lines[5] = f"room={room}\n" - 用加号做字符串拼接:
lines[5] = "room=" + str(room) + "\n"
修复后对应位置的代码片段:
room = input("[#] Change the room value : ") # 替换原有的元组赋值,拼接为合法字符串并保留行尾换行 lines[5] = f"room={room}\n" save = open(path, 'w+') save.writelines(lines) save.close()
可选优化:操作文件时可以用with上下文管理器,不需要手动调用close()方法,能避免程序中途报错时文件句柄没正常释放的问题。
内容的提问来源于stack exchange,提问作者Smoodie
相关产品推荐
相关产品推荐

