I think I know of a way to do this, but I'd like to see if there is a bettery way. So here is the the file for just one part I'm trying to read from (and then write back to)
['Part assembly name', <name of assembled part>]
['Parts', <part1>, <part2>, <part3>]
['Quantities', 5, 8, 2]
['Part category, <category type 1>, <category type 2>]
If I save each line to an array, I can write each one with json
myfile = file('partsList.txt', 'w')
for x in (names, ingedients, volumes, category):
json.dump(x, myfile)
myfile.write('\n')
I should able to read each line back with:
with open(fname) as f:
names.append(f.readlines())
parts.append(f.readlines())
quanties.append(f.readlines())
categories.append(f.readlines())
So after reading all of my different part assemblies from my file I should have four arrays (or maybe 1 2 dimensional array)
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>]
is there a better/easier way to do this? I don't want to try to reinvent the wheel. Thanks!
Use a dictionary, then encode and write once , read and decode once :
with file('partsList.txt', 'w') as myfile:
data = {'names': names, 'ingredients': ingredients, 'volumes': volumes, 'category': category}
json.dump(data, myfile)
Reading:
with file('partsList.txt') as myfile:
data = json.load(myfile)
names = data['names']
# etc.
or better still, start with the dictionary instead of separate variables in the first place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.