I'm in an introductory Python undergraduate class and I'm working on a text file.
An example of its contents can be seen below:
Special Type A Sunflower
2017-10-19 18:20:30
Asteraceae
Brought to the USA by Europeans
Ingredient for Sunflower Oil
Needs full sun
Moist Soil, with heavy mulch
Water only when top 2 inches of soil is dry
Tropical Sealion
2020-04-25 12:10:05
Pinnipeds
Mostly found in zoos
Likes Fish
Likes Balls
Likes Zookeepers
Honey Badger
2018-06-06 16:15:25
Mustelidae
Eats anything
Currently, I'm trying to convert these lines to become the values of a dictionary, by making only 3 keys.
The first key is "Name", the corresponding value would be every first line of every text block.
The second key is "Date", the corresponding value would be every second line of every text block.
The third key is "Information", the corresponding value would be every third line and beyond of every text block, stopping at the space between the text blocks. I believe this should be a list of values too.
My progress is here:
import itertools
import os
MyFilePath = os.getcwd() # absolute directory the file is in
ActualFile = "myplants.txt"
FinalFilePath = os.path.join(MyFilePath, ActualFile)
def TextFileToDictionary():
dictionary_1 = {}
textfile = open(FinalFilePath, 'r')
first_line = textfile.readline()
second_line = textfile.readline()
third_line = textfile.readline()
for line in textfile:
dictionary_1["name"] = first_line
dictionary_1["date"] = second_line
dictionary_1["information"] = third_line
print(dictionary_1)
textfile.close()
TextFileToDictionary()
Although I have parsed the lines as values in a dictionary,
I am unable to iterate them over every text block to ensure all text blocks become dictionary values.
I am also unable to convert every third line and beyond, to become a list of values.
Do note that the text blocks are of uneven lengths.
So the end result should resemble:
dictionary_1 = {'Name' : "Special Type A Sunflower", 'Date' : "2017-10-19 18:20:30", 'Information' : ["Asteraceae, Brought to the USA by Europeans, Ingredient for Sunflower Oil, Needs full sun, Moist Soil, with heavy mulch, Water only when top 2 inches of soil is dry"]}
dictionary_2 = {'Name' : "Tropical Sealion", "Date" : "2020-04-25 12:10:05", "Information" : ["Pinnipeds, Mostly found in zoos, Likes Fish, Likes Balls, Likes Zookeepers"]}
And so on.
Does anyone know how to change the code to resemble the desired end result?
Many thanks!