如何在块文件中写入列表列表

时间:2019-06-17 14:14:34

标签: python python-3.x list file

我有一个看起来像这样的列表列表:

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

我想将该列表写入文件数为预定值的文件中。然后,每个文件中的列表数是所有列表数与文件数的除法。因此,如果:

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

输出将如下所示:

file1.txt

apple
mango
cherry
dog
cat
bird

file2.txt

rose
jasmine
sunflower
hospital
house
school

file3.txt

chair
table
cupboard
book
pencil
pen

这是我尝试过的:

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

我不知道如何解决此问题。我希望有人可以帮助我解决这个问题。谢谢

2 个答案:

答案 0 :(得分:2)

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))

答案 1 :(得分:1)

尝试一下:

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')