You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本文件中的列表读入Python并赋值为列表而非字符串

如何将文件中存储的字符串形式嵌套列表转回列表类型?

你遇到的问题是因为用str()把列表转成字符串写入文件后,读取得到的是字符串对象,直接索引只会取单个字符。以下是两种可靠的解决方法:

方法一:使用ast.literal_eval()(推荐)

ast.literal_eval()专门用于解析Python字面量(比如列表、字典等),比直接用eval()更安全,不会执行恶意代码:

import ast

with open("contacts.txt", "r") as file1:
    contact_str = file1.readline().rstrip()
    contact_list = ast.literal_eval(contact_str)

print(contact_list[0])  # 输出:['Name', 'Email', 'Phone Number']

方法二:使用json模块

由于你的文件内容格式和JSON数组接近,只需将单引号替换为双引号(JSON要求用双引号),即可用json.loads()解析:

import json

with open("contacts.txt", "r") as file1:
    contact_str = file1.readline().rstrip()
    # 替换单引号为双引号,适配JSON格式
    contact_str_json = contact_str.replace("'", "\"")
    contact_list = json.loads(contact_str_json)

print(contact_list[0])  # 输出:['Name', 'Email', 'Phone Number']

后续优化建议

如果以后需要频繁读写这类结构化数据,建议直接用json模块完成存储和读取,避免字符串解析的麻烦:

写入文件

import json

contact_list = [['Name', 'Email', 'Phone Number'], ['Name1', 'Email1', 'Phone Number1']]
with open("contacts.txt", "w") as file1:
    json.dump(contact_list, file1)

读取文件

import json

with open("contacts.txt", "r") as file1:
    contact_list = json.load(file1)

内容的提问来源于stack exchange,提问作者Usmish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:46:12