How to write list of list in chunk file

Viewed 116

I have list of list that looks like this:

listThing = [['apple','mango','cherry'],
             ['dog','cat','bird'],
             ['rose','jasmine','sunflower']
             ['hospital','house','school']
             ['chair','table','cupboard']
             ['book','pencil','pen']]

I want to write that list into files where the number of files is a predetermined value. Then, the number of lists in each file is the division of the number of all lists and number of files. So if:

number of file = 3
number of list in each file = number of all lists/number of file = 6/3 = 2

The outputs will look like this:

file1.txt

apple
mango
cherry
dog
cat
bird

file2.txt

rose
jasmine
sunflower
hospital
house
school

file3.txt

chair
table
cupboard
book
pencil
pen

This is what I've tried:

import math

allList = len(listThing)
numFile = 3
listInFile = math.ceil(allList/numFile)

for i in range(listInFile):
    with open('file'+str(i)+'.txt', 'w') as out:
        for n in range(listInFile):
            # I don't know what should I do next

I do not know how to solve this problem. I'm hoping someone can help me to solve this problem. Thank you

2 Answers
import math    

list_of_lists = [['apple', 'mango', 'cherry'],
                 ['dog', 'cat', 'bird'],
                 ['rose', 'jasmine', 'sunflower'],
                 ['hospital', 'house', 'school'],
                 ['chair', 'table', 'cupboard'],
                 ['book', 'pencil', 'pen']]

num_files = 3
all_lists = len(list_of_lists)

lists_per_file = math.ceil(all_lists / num_files)

for i in range(1, num_files + 1):
    with open("file{}.txt".format(i), "w") as file:
        lst_idx = (i-1)*lists_per_file
        for lst in list_of_lists[lst_idx:lst_idx+lists_per_file]:
            for word in lst:
                file.write("{}\n".format(word))

Try this:

import math

listThing = [['apple','mango','cherry'],
             ['dog','cat','bird'],
             ['rose','jasmine','sunflower'],
             ['hospital','house','school'],
             ['chair','table','cupboard'],
             ['book','pencil','pen']]

allList = len(listThing)
numFile = 3
listInFile = int(math.ceil(allList/numFile))
currentFileIndex = None

for e, lt in enumerate(listThing):
    fileIndex = 1 + int(math.floor(e / listInFile))
    if currentFileIndex != fileIndex:
        currentFileIndex = fileIndex
        currentFile = open('file%d.txt' % fileIndex, 'wb')
    for entry in lt:
        currentFile.write(entry.encode('utf8'))
        currentFile.write(b'\n')
Related