Patrick
Patrick

Reputation: 21

Writing multiple lists to a single column

I want to read a 2 column file like this:

1 3
4 7
2 8

and get back a single column file like this:

3
7
7
7
7
8
8

Here's my code:

import csv
array1 = []
array2 = []
with open('test.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        array1.append(row[0])
        array2.append(row[1])
range1 = len(array1)
array1 = [int(x) for x in array1]
array2 = [int(x) for x in array2]

outfile = open('drp', 'wb')
writer=csv.writer(outfile)

for s in range(0, range1, 1):
            res = [array2[s]] * array1[s]
            print res
            writer.writerow([res])
outfile.close()  

It seems to be working except for the final writing step. What I get in my output file is:

[3]  
"[7, 7, 7, 7]"  
"[8, 8]"

Obviously I'm not using the csv writer correctly. Any suggestions? Thanks.

Upvotes: 1

Views: 125

Answers (4)

Moh Zah
Moh Zah

Reputation: 292

Is there any special reason you read a text file in binary mode or using csv?

with open('test.txt', 'r') as f, open('drp','w') as ff::
     for l in f:
         a,b=l.split(' ')
         for i in range(int(a)):
             ff.write(b+'\n')

Upvotes: 0

iruvar
iruvar

Reputation: 23394

Another option

from itertools import chain
with open('test.txt') as f:
    z = (line.split() for line in f)
    print '\n'.join(chain.from_iterable(int(x)*[y] for (x, y) in z))

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 114035

This should do it

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        mult, val = line.strip().split()
        outfile.write('\n'.join([val for _ in xrange(int(mult))]))
        outfile.write('\n')

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251156

You're over complicating this simple problem:

import csv
with open('test.txt') as f, open('out.csv','w') as f2:
    writer = csv.writer(f2, delimiter = '\n')
    for line in f:
        x, y = line.split() 
        writer.writerow([y]*int(x))

output:

>>> cat out.csv
3
7
7
7
7
8
8

Upvotes: 1

Related Questions