如何将文件中的复杂内容加载到Python程序中?

2024-10-02 08:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程作业的输入有问题:

People in a town go shopping many times on a weekly basis. The town mayor wants to keep track of how many items a person buys every time they go shopping. He is only monitoring three houses. In each house, there are five members of the family. The data for each family should be kept separately. Code to solve this program.

现在,必须将文件内容加载并保存到文件中。 我已经计划好输入(对于第一个任务)在文件本身中如下所示,并且我希望它在加载到程序中时显示为这样:

[['James',0],['Katherine',0],['Jacob',0],['Michael',0],['Cyndia',0]]

但是,我现在的代码是:

Class11A = []

def Class(FileLabel,FileName,ReadLabel,Class):

    FileLabel = open(FileName,mode = 'r+')
    ReadLabel = FileLabel.read()
    for line in ReadLabel:
        Class.append(line)

Class('Class11A','Class 11A.txt','Class11ATempList',Class11A)
print (Class11A)

然而,代码加载的内容如下:

['[', '[', "'", 'J', 'a', 'm', 'e', 's', "'", ',', '0', ']', ',', '[', "'", 'K', 'a', 't', 'h', 'e', 'r', 'i', 'n', 'e', "'", ',', '0', ']', '[', "'", 'J', 'a', 'c', 'o', 'b', "'", ',', '0', ']', '[', "'", 'M', 'i', 'c', 'h', 'a', 'e', 'l', "'", ',', '0', ']', '[', "'", 'C', 'y', 'n', 'd', 'i', 'a', "'", ',', '0', ']', ']']

我该怎么解决这个问题?你知道吗

注意:将使用相同的文件结构加载其他两个族的数据。你知道吗


Tags: 文件ofthetoingofamilymany
1条回答
网友
1楼 · 发布于 2024-10-02 08:14:46

主要问题是read()读取整个文件。ReadLabel现在是整个文件内容的字符串。你的命名似乎认为它仍然是一行一行的形式,但它只是一个字符串。因此,仅仅是一系列字符,您可以将它们单独附加到列表中。你知道吗

一种可能的修复方法是使用eval()操作将字符串转换为列表:

family_list = eval(ReadLabel)

这将为您提供五个列表。举例说明:

target = "[['James',0],['Katherine',0],['Jacob',0],['Michael',0],['Cyndia',0]]"
target_list = eval(target)
print len(target_list), target_list[1]

这就产生了输出

5 ['Katherine', 0]

我希望这能让你摆脱困境。你仍然有许多小决定要做或修理。你知道吗

相关问题 更多 >

    热门问题