0

I have a huge list with 9000 items. I already referred this post here and here. Don't mark it as duplicate

Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,0898]

I would like to split my list and store the output of each list in a notepad file

For ex: I wish each of my output list to contain ~10% of items from the original Mylist

So, I tried the below

for k,g in itertools.groupby(Mylist, lambda x: x/10):
      with open("part1.txt", 'w') as file:
      file.write('\n'.join(yourList))

I expect my output to have multiple text files like below and each file should contain 10% of items stored like below in screenshot from original list

part1.txt
part2.txt
part3.txt
part4.txt

enter image description here

BENY
  • 317,841
  • 20
  • 164
  • 234
The Great
  • 7,215
  • 7
  • 40
  • 128

1 Answers1

1

No need for groupby, a simple loop with slicing is sufficient. You need to decide how to handle the extra items (add to the last list or add an extra file):

Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,898]
N = 3 # use 10 in your real life example

step = len(Mylist)//N
start = 0
for i, stop in enumerate(range(step, len(Mylist)+step, step)):
    print(f'file{i}')
    print(Mylist[start:stop]) # save to file here instead
    start = stop

output:

file0
[1234, 45678, 2314, 65474]
file1
[412, 87986, 21321, 4324]
file2
[68768, 1133, 712421, 12132]
file3
[898]

Variant for adding to last file:

Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,898]
N = 3

step = len(Mylist)//N
start = 0

for i, stop in enumerate(range(step, len(Mylist), step)):
    print(f'file{i}')
    if i+1 == N:
        stop = len(Mylist)
    print(Mylist[start:stop]) # save to file here instead
    start = stop

output:

file0
[1234, 45678, 2314, 65474]
file1
[412, 87986, 21321, 4324]
file2
[68768, 1133, 712421, 12132, 898]
saving to file
Mylist = [1234,45678,2314,65474,412,87986,21321,4324,68768,1133,712421,12132,898]
N = 3

step = len(Mylist)//N
start = 0

for i, stop in enumerate(range(step, len(Mylist), step), start=1):
    if i == N:
        stop = len(Mylist)
    with open(f'file{i}.txt', 'w') as f:
        f.write(','.join(map(str,Mylist[start:stop])))
    start = stop
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Can update your answer to include export to notepad file? – The Great May 22 '22 at 14:19
  • because when I export, each item in the list are stacked one by one. each item is in one line, But I want my output to look like how I have shown in screenshot above – The Great May 22 '22 at 14:20