I have a file that I wanted to group into list. The data are separated by empty lines. How to parse the data properly to get the needed output?
mydata.txt
introA
aboutA1
aboutA2
aboutA3
aboutA4
introB
aboutB1
aboutB2
aboutB3
aboutB4
Current Code:
with open("mydata.txt", "r") as f:
data = [line.strip() for line in f if line.strip()]
print (data)
Current Output:
['introA', 'aboutA1', 'aboutA2', 'aboutA3', 'aboutA4', 'introB', 'aboutB1', 'aboutB2', 'aboutB3', 'aboutB4']
Needed Output:
"introA":['aboutA1', 'aboutA2', 'aboutA3', 'aboutA4',],
"introB":['aboutB1', 'aboutB2', 'aboutB3', 'aboutB4',],
>Solution :
Here’s a simple example
wordlist = {}
current_header = None
with open("mydata.txt", "r") as f:
for line in f:
line = line.rstrip('\n')
if not line:
current_header = None
continue
if not current_header:
current_header = line
wordlist[current_header] = []
if current_header != line:
wordlist[current_header].append(line)
print(wordlist)