2

I'm supposed to create a "stock control" system for a software wholesaler for an module assignment. I have created the program, but I'm having trouble saving stuff permanently. The program consists of nested lists like the following:

[["Ms Office", "CD", 7, "Microsoft"], ["Acrobat Reader", "DVD", 12, "Adobe"], ["Norton Antivirus", "DVD", 24, "Symantec"]]

I can save them to a text document in the format

['Ms Office', 'CD', 7, 'Microsoft']
['Acrobat Reader', 'DVD', 12, 'Adobe']
['Norton Antivirus', 'DVD', 24, 'Symantec']

But when I try to load it back as a list in the same format, I end up with quotation marks separating each entry like so:

["['Ms Office', 'CD', 7, 'Microsoft']", "['Acrobat Reader', 'DVD', 12, 'Adobe']", "['Norton Antivirus', 'DVD', 24, 'Symantec']"]

I just need to get rid of the double quotes surrounding each item in the list now. The code I'm using to load this file:

filename = open('Appexstock.txt', 'r')
contents = filename.read()
thelist = [name for name in contents.split('\n') if name.split('"') if name]
filename.close()

I've searched for hours online and have tried everything but I still can't find a way to make it work. I've seen a lot of people suggest the CSV module, but I have no idea how to apply it to my code.

4

1 回答 1

2

使用ast.literal_eval

>>> from ast import literal_eval
with open('Appexstock.txt') as f:
    lis = [literal_eval(line) for line in f]
...     
>>> lis
[['Ms Office', 'CD', 7, 'Microsoft'], ['Acrobat Reader', 'DVD', 12, 'Adobe'], ['Norton Antivirus', 'DVD', 24, 'Symantec']]

要存储 python 对象,最好使用pickle模块:

>>> import pickle
>>> data = [["Ms Office", "CD", 7, "Microsoft"], ["Acrobat Reader", "DVD", 12, "Adobe"], ["Norton Antivirus", "DVD", 24, "Symantec"]]
with open('my_data', 'w') as f:
    pickle.dump(data, f)
...     
with open('my_data') as f:
    print pickle.load(f)
...     
[['Ms Office', 'CD', 7, 'Microsoft'], ['Acrobat Reader', 'DVD', 12, 'Adobe'], ['Norton Antivirus', 'DVD', 24, 'Symantec']]
于 2013-09-21T15:32:07.753 回答