Reputation: 607
So to put it simply lets say have data in a file that begins with
Start
47 Data
70 Data
60 Data
Finish
Start
56 Data
86 Data
75 Data
Finish
How do I read in the file and have each data within the Start and Finish sorted respectively?
The Output would look liek
Start
47 Data
60 Data
70 Data
Finish
Start
56 Data
75 Data
86 Data
Finish
I really don't know how to apply the sort method selectively?
Upvotes: 0
Views: 33
Reputation: 140168
you could make a list of lists, store each block in a list, then sort all lists:
data = []
with open("data.txt") as f:
for l in f:
l = l.strip()
if l: # discard empty lines
if l=="Start":
# create a new list
data.append([])
elif l=="Finish": # we don't really need that tag, we have "Start"
pass
else:
data[-1].append(l) # append to current list (last one)
# list comprehension to order sub-lists
sorted_data = [sorted(d) for d in data]
# print sorted in console
for d in data:
print("Start")
for i in d:
print(i)
print("Finish\n")
Upvotes: 2