Split a list in python into different text files

2020-04-20 20:57发布

I want to write three separate text files for each three element of the list below:

my_list = ['text1', 'text1', 'text1', 'text2', 'text2', 'text2', 'text3', 'text3', 'text3']
result = [my_list[idx:idx + 3] for idx in range(0, len(my_list), 3)]
outfiles = ['file1', 'file2', 'file3']
for f in outfiles:
    with open ('{}.txt'.format(f),'w') as fo:
        for x in result:
            for y in x:
                fo.write(str(y) + '\n')

Please help me correcting the code above.

file1 should consist:

text1
text1
text1

file2:

text2
text2
text2

file3:

text3
text3
text3

But my code above writes:

text1
text1
text1
text2
text2
text2
text3
text3
text3

标签: python
3条回答
手持菜刀,她持情操
2楼-- · 2020-04-20 21:33
outfiles = ['file1', 'file2', 'file3']
my_list = ['text1', 'text1', 'text1', 'text2', 'text2', 'text2', 'text3', 'text3', 'text3']
for i in range(0, len(my_list), len(outfiles)):
    with open(my_list, 'a') as outfile:
        for line in outfiles[i:i+len(my_list)]:
            outfile.write(line)
            outfile.write('\n')

The following can be done with minimal edits to your code:

outfiles = ['file1', 'file2', 'file3']
my_list = ['text1', 'text1', 'text1', 'text2', 'text2', 'text2', 'text3', 'text3', 'text3']

round = 0
i = 0
while len(files)*round + i < len(my_list):
    for i,outfilepath in enumerate(outfiles):
        with open(outfilepath) as outfile:
            outfile.write(my_list[len(files)*round + i])
    i += 1
查看更多
贪生不怕死
3楼-- · 2020-04-20 21:34

You can try this using a loop to iterate over a slice of the list. Here, we are using the variable i to indicate which slice of the list will be used in each iteration:

my_list = ['text1', 'text1', 'text1', 'text2', 'text2', 'text2', 'text3', 'text3', 'text3']
outfiles = ['file1', 'file2', 'file3']

i = 0 # to keep count of which words will be written
for f in outfiles:
    with open ('{}.txt'.format(f), 'w') as fo:
        for word in my_list[i:i + 3]:
            fo.write(word + "\n")
    i += 3
查看更多
▲ chillily
4楼-- · 2020-04-20 21:43

I would probably use itertools.groupby here ...

for i, (k, group) in enumerate(groupby(my_list), 1):
    with open('file{}.txt'.format(i), 'w') as fout:
        fout.writelines(item + '\n' for item in group)
        # fout.write('\n'.join(group))  # another alternative which doesn't write a newline at the end of the file.

This assumes that the initial list was sorted and it seems a little silly to write the same thing to a file over and over, but if you really have a more diverse list, you can always sort and group by the result of some key function which would be applied to each element in the list...

查看更多
登录 后发表回答