0

I want to:

  1. Import CSV formatted data into a python list/array

  2. Right justify a 8 space field for the string

  3. Write the output as a text file

For example, I want to turn csv data such as:

11111, 22,

333, 4444

Into:

   11111      22

     333    4444

My code currently looks like:

import csv

input_file = "csv_file.csv"
my_data = csv.reader(open(input_file, "rb"), delimiter=',')

for i,j in my_data:
    x = ('%-15s %s\n' % (i,j))

with open('my_output.txt', 'w') as file:
    file.writelines(x)

Thank you

user1183643
  • 49
  • 2
  • 5

1 Answers1

1

I would just rjust each element individually and ''.join them:

''.join(elem.rjust(8) for elem in (i,j))

Or to write it all out:

def join_line(line_iter):
    """
    Take a iterable containing strings and right justify each 
    at 8 spaces before joining
    """
    return ''.join(elem.rjust(8) for elem in line_iter)

with open('output','w') as f:
    f.writelines((join_line(row)+'\n') for row in csv_file)
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Thanks mgilson. Your code works perfectly. If I want to give 8 spaces to column 1 and 16 spaces to column 2…how would I alter the join_line def? Thanks again – user1183643 Jan 10 '13 at 08:18
  • Then I think it's better to be explicit: `f.writelines(col1.rjust(8)+col2.rjust(16)+'\n' for col1,col2 in csv_file` – mgilson Jan 10 '13 at 10:43
  • Thanks a lot mgilson. Another great suggestion – user1183643 Jan 10 '13 at 11:00