Python如何将嵌套列表按指定格式循环写入TXT文本文档
Python格式化写入文本文件实现方案
原有代码存在的问题
- 循环内部以
w覆盖写模式打开文件,每轮循环都会清空文件已有内容,最终仅会保留最后一次写入的内容 - 直接将嵌套列表整体转为字符串写入,未按需求拆分格式
- 未主动添加换行符,导致所有内容挤在同一行
修正后代码(强制使用while循环实现)
def write_to_file(filename, character_list): index = 0 # 文件打开操作放在循环外,避免重复打开清空内容、提升执行效率 with open(filename, "w", encoding="utf-8") as output: # while 循环遍历每个角色的信息子列表 while index < len(character_list): current_char = character_list[index] # 前两项为角色名、真实名,各单独占一行 output.write(current_char[0] + "\n") output.write(current_char[1] + "\n") # 后续属性统一转为字符串后用空格拼接为一行 attr_line = " ".join(str(item) for item in current_char[2:]) + "\n" output.write(attr_line) index += 1
调用示例
# 测试数据 char_list = [['Wonder Woman', 'Diana Prince', 'h', 5, 5, 0, 0, 90], ['Batman', 'Bruce Wayne', 'h', 6, 2, 0, 4, 80]] # 调用函数写入文件 write_to_file("new_characters.txt", char_list)
执行后生成的文件内容完全匹配要求的输出格式。
内容的提问来源于stack exchange,提问作者Jayden
相关产品推荐
相关产品推荐

