raddirad
raddirad

Reputation: 331

Python write text to CSV with two columns

Hi I have a small problem here.

I have a text file with numbers which looks like this

2.131583
2.058964
6.866568
0.996470
6.424396
0.996004
6.421990

And with

fList = [s.strip() for s in open('out.txt').readlines()]
outStr = ''
for i in fList:
      outStr += (i+',')
f = open('text_to_csv.csv', 'w')
f.write(outStr.strip())
f.close()

I am able to generate a CSV and all the data is stored in it, but all in one row. I would like to have them in two columns.

Is there any easy addition that would make the CSV look like this?

2.131583 2.058964
6.866568 0.996470
6.424396 0.996004

Upvotes: 1

Views: 3652

Answers (6)

Acuda
Acuda

Reputation: 66

I'am not really sure what you mean, but i think your expected output is:

2.131583,2.058964,
6.866568,0.996470,
6.424396,0.996004,
6.421990

My code for this:

with open('out.txt', 'r') as fif, open('text_to_csv.csv', 'w') as fof:
    fList = ','.join([v.strip() if i % 2 else '\n'+v.strip()
                      for i, v in enumerate(fif.readlines())])[1:]
    fof.write(fList)


Interesting points:

If you want to get rid of the trailing "," at the end of your file, just concatenate the list via the join() function.

flat_string = ','.join([item1,...,])

For leading linebreak on odd-items in the list i have enumerated it.

index, value enumerate([item1,...,])

And find the odd-items via the modulo-operator index % 2.

With an "inline-if" you can check this on the fly.

At least i exclude the redundant linebreak at the beginning on the string with [1:]

Upvotes: 0

dawg
dawg

Reputation: 103959

If you have a list (from reading the file) in memory, just reformat the list into what you want:

input='''\
2.131583
2.058964
6.866568
0.996470
6.424396
0.996004
6.421990'''    

cols=2

data=input.split()       # proxy for a file
print data
print '==='
for li in [data[i:i+cols] for i in range(0,len(data),cols)]:
    print li

Prints:

['2.131583', '2.058964', '6.866568', '0.996470', '6.424396', '0.996004', '6.421990']
===
['2.131583', '2.058964']
['6.866568', '0.996470']
['6.424396', '0.996004']
['6.421990']

Or, use a N-at-a-time file reading idiom:

import itertools
cols=2
with open('/tmp/nums.txt') as fin:
    for li in itertools.izip_longest(*[fin]*cols):
        print li  
# prints
('2.131583\n', '2.058964\n')
('6.866568\n', '0.996470\n')
('6.424396\n', '0.996004\n')
('6.421990', None)

Which you can combine into one iterator in, one iterator out if you want a type of file filter:

import itertools
cols=2
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
    for li in itertools.izip_longest(*[fin]*cols):
        fout.write('\t'.join(e.strip() for e in li if e)+'\n')

The output file will now be:

2.131583    2.058964
6.866568    0.996470
6.424396    0.996004
6.421990

If you only want to write the output of there are the full set of numbers, i.e., the remainder numbers at the end of the file that are less than cols in total length:

import itertools
cols=2
# last number '6.421990' not included since izip is used instead of izip_longest
with open('/tmp/nums.txt') as fin, open('/tmp/nout.txt','w') as fout:
    for li in itertools.izip(*[fin]*cols):
        fout.write('\t'.join(e.strip() for e in li)+'\n') 

Then the output file is:

2.131583    2.058964
6.866568    0.996470
6.424396    0.996004

Upvotes: 0

Karthik
Karthik

Reputation: 142

A better way would be using csv module. You can write like

import csv

with open('text_to_csv.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',quoting=csv.QUOTE_MINIMAL)
    for i in range(0, len(fList), 2):
        writer.writerow(fList[i:i+2])

Upvotes: 2

brm
brm

Reputation: 3806

If you're not interested in storing the entries from the original file in a new list but just want the output file, you can also do something like this:

fList = [s.strip() for s in open('out.txt').readlines()]
f = open('text_to_csv.csv', 'w')
for i in range(0,len(fList)-1,2):
    f.write(fList[i] + "," + fList[i+1] + "\n")

f.close()

Upvotes: 0

Ricardo Villamil
Ricardo Villamil

Reputation: 5107

Something like this:

with open('out.txt', 'r') as fList, open('text_to_csv.csv', 'w') as f:
    i = 0
    for line in fList:
        f.write(line)
        f.write('\n' if i% 2 == 0 else '\t')`

Upvotes: 0

andrewgrz
andrewgrz

Reputation: 423

fList = [s.strip() for s in open('out.txt').readlines()]
outStr = ''
count = 0
for i in fList:
      outStr += (i+',')
      if count % 2 == 0: # You can replace 2 with what ever number you of columns you need
          outStr += ('\r\n') # Make the return correct for your system
      count += 1
f = open('text_to_csv.csv', 'w')
f.write(outStr.strip())
f.close()

Upvotes: 1

Related Questions