0

There is a dataset as a csv-file which contains some tabular of data.
I want to pick out the fractions with the same number.
For example i have one list

a = [1,1,2,2,3,3,4,4,4,5,5,5,5,6]

and i want a loop, which writes text-files with the same numbers
file_1.txt contains 1,1
file_2.txt contains 2,2
file_3.txt contains 3,3
file_4.txt contains 4,4,4
file_5.txt contains 5,5,5,5
file_6.txt contains 6

I still have no real result, because so far everything is wrong.

Ala Tarighati
  • 3,507
  • 5
  • 17
  • 34
deptrai
  • 147
  • 1
  • 9

2 Answers2

0

If I understood correctly, this should work:

for x in set(a):
    text_file = open("file_"+str(x)+".txt", "w")
    text_file.write(((str(x)+',')*a.count(x))[:-1])
    text_file.close()

Where that [:-1] in the third line is to remove extra comma ;)

Ala Tarighati
  • 3,507
  • 5
  • 17
  • 34
0

A much cleaner approach would be to use itertools.groupby and str.join:

from itertools import groupby

for num, group in groupby(a):
    filename = "file_%d.txt"%num
    with open(filename, 'w') as f:
        f.write(",".join(map(str, group)) + "\n")

Another important point is that you should always use the with statement when reading and writing to files.


Using groupby assumes that the data is already sorted. Another approach would be to use collections.Counter:

from collections import Counter

for num, count in Counter(a).items():
    filename = "file_%d.txt"%num
    with open(filename, 'w') as f:
        f.write(",".join([str(num)]*count) + "\n")
pault
  • 41,343
  • 15
  • 107
  • 149