hiram321 发表于 2021-11-29 12:53:06

读取txt

1 piece of chicken, 3
6 pieces of chicken, 14.95
21 pieces of chicken, 34.95


怎么读取这个txt才能变成下面列表套列表的形式
[["1 piece of chicken", 3], ["6 pieces of chicken", 14.95], ["21 pieces of chicken", 34.95]]

jackz007 发表于 2021-11-29 13:30:14

f = open('data.txt')
d =
f . close()
for x in d:
    x = eval(x)
print(d)
      运行实况:
D:\00.Excise\Python>python x.py
[['1 piece of chicken', 3], ['6 pieces of chicken', 14.95], ['21 pieces of chick
en', 34.95]]

D:\00.Excise\Python>

lightninng 发表于 2021-11-29 13:40:48

本帖最后由 lightninng 于 2021-11-29 13:43 编辑

请把楼上设为最佳,我从他那学到了eval函数,哈哈哈哈哈哈哈哈
with open("score1.txt","r") as fp:
    result=[ for item1,item2 in ]

z5560636 发表于 2021-11-29 13:45:50

lightninng 发表于 2021-11-29 13:40
请把楼上设为最佳,我从他那学到了eval函数,哈哈哈哈哈哈哈哈

eval甚至可以用于执行windws命令行的命令。
页: [1]
查看完整版本: 读取txt