2015-11-02 58 views
-4

我无法与输入的编程任务:如何将文件中的复杂内容专门加载到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', ']', ']'] 

如何解决这个问题?

注意:将使用相同的文件结构来加载其他两个系列的数据。

+0

你能解释一下你的功能应该做什么吗?该名称不具有描述性,并且非常类似于Python保留字。您为其中一个参数使用*相同*名称。你从不使用第三个参数的值。您对数据表示的选择很好奇:Python变量的默认打印表示对于存储值通常不是特别有用。 – Prune

+0

这不是一个很好的方式来存储您的名字,访问.... –

回答

1

主要问题是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] 

我希望这可以让你粘住。你仍然有很多小的决定要做或修理。

+0

如何通过@Prune从文件输入? – Anonymous42673849503

+0

使用** readline **代替** ** **。有关基本输入和输出,请参见[7.2](https://docs.python.org/2/tutorial/inputoutput.html)。 – Prune

+0

应如何存储文件中的内容?对不起,我还没有完全掌握这一点。 @Prune – Anonymous42673849503

相关问题