Saravana Murthy
Saravana Murthy

Reputation: 553

Writing to a specific column of a text file in python

I have an array of 6 string characters which are of the datatype string and I have to write them in 1,16,19,22,51,54th position of a line respectively in a text file using python to be properly read by a software.

The array looks like

[ABCD, 1, P, 15-06-2015, 0, Name of the account]

The first element of the array is always a 4 or 5 letter string. (should start from 1st position of the line or first column of the line) The second element is always a single digit ( should start at 16) The third element is always a single alphabet (should start at 19) The fourth element is a date (should start at 22) The fifth element is again a single digit (should start at 51) The sixth element is a varying string which contains comments about the array (should start at 54)

Also after the sixth element there should be white spaces till 134th column

How can I do this in python automatically because I have to similarly write 200 lines.

Thanks in advance.

Upvotes: 1

Views: 3128

Answers (2)

scope
scope

Reputation: 1997

This could be done with simple string formatting:

arr = ['ABCD', '1', 'P', '15-06-2015', '0', 'Name of the account']
print "{:16}{:3}{:3}{:29}{:3}{:40}".format(*arr)

Values there are not positions but lengths of each item.

EDIT

If items in your array are not only strings but also numbers it will still work, though you will probably want them left aligned (strings are by default):

arr = ['ABCD', 1, 'P', '15-06-2015', 0, 'Name of the account']
print "{:16}{:<3}{:3}{:29}{:<3}{:40}".format(*arr)

Here's doc.

Upvotes: 3

tnknepp
tnknepp

Reputation: 6263

I assume your "array" is a numpy array. If the formatting of your array is a strict as you say, then you should be able to write as follows:

# assume array is called A
with open('filename.txt', 'r') as fid:
    for r in xrange(A.shape[0]):
        A[r].tofile(fid, sep=', ')

If your array is really a list:

with open('filename.txt', 'r') as fid:
    for r in A:
        fid.write( ', '.join(r) )

Of course, this depends on your array containing only strings. I understand you said that there are strings, integers, and dates, within your array, but I assume you mean they are all strings. If that is not the case, then you can correct for this by including a simple type conversion in the loops.

Upvotes: 0

Related Questions