I have a.txt file of the following but each value starting on the next line
229
flowers
7
2.99
456
bows
3
19.99
I originally coded for them as if they were separated by commas instead of starting on the next line with this code:
inventory_dict = {}
#open inventory
inventory_data = open(INVENTORY_FILE,'r')
#read
for line in inventory_data:
values = line.split(',') #split items using commas
item_id = values[0]
name = values[1] #<-- storing the info in separate variables
quantity = int(values[2])
price = float(values[3])
inventory_item = inventory.Inventory(item_id,name,quantity,price)#create an instance
inventory_dict[item_id] = inventory_item
` How do i do the same thing, but using the fact that each value starts on a different line as the separator?
I've tried using \n as a separator and that hasn't worked either.
You need to consume four lines at a time from the file, so a plain for line in file
loop won't work.
Try this:
# read all the lines in the file
inventory = open(INVENTORY_FILE,'r').readlines()
# keep looping if there are at least four more lines remaining
while len(inventory) >= 4:
# .pop(0) removes the first item in the list
item_id = inventory.pop(0)
name = inventory.pop(0)
quantity = int(inventory.pop(0))
price = float(inventory.pop(0))
# now assign to dict...
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.