【问题标题】:How to write list of list in chunk file如何在块文件中写入列表列表
【发布时间】:2019-10-31 03:45:44
【问题描述】:

我的列表如下所示:

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

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

【问题讨论】:

  • for 循环中有什么代替 ...?你为那部分做了什么
  • 问题出在哪里?
  • @DeveshKumarSingh 抱歉,我已经更新了问题

标签: python python-3.x list file


【解决方案1】:
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))

【讨论】:

  • 你是不是偷看了我的回答,改了几行?你个鲨鱼!有一个updoot
【解决方案2】:

试试这个:

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

【讨论】:

  • 为什么我会出错:TypeError: a bytes-like object is required, not 'str' in line :currentFile.write(entry)
  • 你正在使用 python3.给我一秒钟。完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 2020-04-20
  • 2014-06-27
  • 2017-12-21
  • 2011-02-23
相关资源
最近更新 更多