Question

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

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top