dedpo dedpo - 1 month ago 9x
Python Question

Writing a list of lists to a seperate text file, one file per a list with in that list

so I am trying to write a list of lists to seperate files.
Each list contains 100 string objects or less. The goal is keep a text file less than 100 lines no more than that.

To do that, i split a list but now i am having an issue writing them to a file.
So essentialy write a list within a list to its own separate file. There are total of 275 strings objects in total

list_ofList_flows=[parameter_list[i:i+size] for i in range(0,len(parameter_list), size)]
#above list_ofList_flows contains [100][100][75] in terms of length

fileNumbers = int(math.ceil((len(parameter_list) / 100)))
#fileNumbers is 3, because we have 3 sets of lists[100, 100, 75]

i = 0
while i < fileNumbers:

for flowGroup in list_ofList_flows:
f = open("workFlow_sheet" + str(i) + ".txt", "w")

for flo in flowGroup:
f.write(flo + '\n')

i = i + 1


Something like this would work. I had to use random to generate some data, into a list that was 275 elements long.

import random

def chunks(l, n):
    n = max(1, n)
    return [l[i:i + n] for i in range(0, len(l), n)]

data = [random.randint(0, 10) for x in range(275)]

chunked_data = chunks(data, 100)

iterator_count = 0
for sublist in chunked_data:
    with open("workFlow_sheet{}.txt".format(iterator_count), 'w') as outfile:
        for item in sublist:
            outfile.write(str(item) + '\n')
    iterator_count += 1

Essentially, sub-divide your data into nested lists of maximum length of 100, and then write the contents of each nested list to a unique file.