full = {}
arr = []
with open('numbers.txt', 'r') as nums:
while True:
read = nums.readline()
if len(read) > 0:
if len(read) == 6:
read = read[:5]
arr.append(read)
elif len(read) < 6:
read = read[0]
full[read] = arr
arr = []
else:
break
with open('numbers.csv', 'w') as csv:
for i in full:
for j in full[i]:
line = str(j) + ',' + str(i) + '\n'
csv.write(line)
This file takes a text file (I copied what you posted above and saved to a text file) and outputs it in a .csv file the way you described.
Sorry for lack of comments, I did it quickly. If you want to modify and don't understand anything just ask and I'll explain.
Also, the way it is now, the program will only work for single digit group numbers. The following change will fix this for numbers up to 4 digits (obviously 5 digits will break it because it won't be able to differentiate between set numbers and their containing elements:
Change the line
read = read[0]
to
read = read[0:len(read)-2]
and it works. Except that it orders them alphabetically rather than numerically, so it goes 11, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9.