Reputation: 502
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
size=100
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
Upvotes: 0
Views: 60
Reputation: 13175
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)
for file_num, sublist in enumerate(chunked_data):
with open("workFlow_sheet{}.txt".format(file_num), 'w') as outfile:
for item in sublist:
outfile.write(str(item) + '\n')
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.
EDIT
I couldn't actually reproduce your problem in terms of each file containing the same data. However, you incremented i
in the wrong scope (it needs an extra level of indentation, I think you overwrote each file multiple times in your code) and you did not close()
the files on each iteration. The use of with
(the Python context manager) just means that it automatically closes the file once the operations are complete. I think this is a working tweak of your original code... albeit with a random list generated.
import random
import math
parameter_list = [random.randint(0, 10) for x in range(275)]
size=100
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(str(flo) + '\n')
f.close()
i = i + 1
Upvotes: 1