我想我知道一种方法可以做到这一点,但我想知道是否有一种赌博方式。所以这里是我试图读取的一个部分的文件(然后写回)
['Part assembly name', <name of assembled part>]
['Parts', <part1>, <part2>, <part3>]
['Quantities', 5, 8, 2]
['Part category, <category type 1>, <category type 2>]
如果我将每一行保存到一个数组,我可以用json
编写每一行myfile = file('partsList.txt', 'w')
for x in (names, ingedients, volumes, category):
json.dump(x, myfile)
myfile.write('\n')
我应该能够阅读每一行:
with open(fname) as f:
names.append(f.readlines())
parts.append(f.readlines())
quanties.append(f.readlines())
categories.append(f.readlines())
所以在从我的文件中读取所有不同的零件组件后,我应该有四个数组(或者可能是1个二维数组)
names = [<name of assembly 1>, <name of assembly 2>, <name of assembly 3>]
parts = [<array of parts for 1>, <array of parts for 2>, <array of parts for 3>]
quantites = [<array of quantites for 1>, <array of quantites for 2>, <array of quantites for 3>]
categories= [<array of categoriesfor 1>, <array of categoriesfor 2>, <array of categoriesfor 3>]
有更好/更简单的方法吗?我不想尝试重新发明轮子。谢谢!
答案 0 :(得分:1)
使用字典,然后编码并写入一次,读取并解码一次:
with file('partsList.txt', 'w') as myfile:
data = {'names': names, 'ingredients': ingredients, 'volumes': volumes, 'category': category}
json.dump(data, myfile)
读:
with file('partsList.txt') as myfile:
data = json.load(myfile)
names = data['names']
# etc.
或者更好的是,首先是字典而不是单独的变量。