[Solved] How to add values to existing columns in a text file (using Python)


what about

a = [1, 2, 3, 4, 5, 6, 7, 8]

f = open('myFile.txt', 'a')
for n in a:
    f.write('%d\t'%n)
f.write('\n')
f.close()

and you get as file content after running it 4 times

1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8

======= EDIT =========

Try this, its ugly but works 😉

import os.path

h = ['Header 1', 'Hea 2', 'Header 3', 'Header    4', 'H 5', 'Header', 'Header 7', 'Header 8']
a = [1, 2, 3, 4, 5, 6, 7, 8]

fileName="myFile.txt"

#write header
withHeader = not os.path.isfile(fileName)

f = open(fileName, 'a')
if withHeader:
    print 'Writing header'
    for s in h:
        f.write('%s\t'%s)
    f.write('\n')

#write numbers
for i in range(0, len(a)):
    space = len(h[i])/2;
    n = a[i]
    for c in range(0, space):
        f.write(' ')
    print 'Writing %d'%n
    f.write('%d'%n)
    for c in range(0, space):
        f.write(' ')
    f.write('\t')
f.write('\n')
f.close()

result:

Header 1    Hea 2   Header 3    Header    4 H 5 Header  Header 7    Header 8    
    1         2         3            4       5     6        7           8       
    1         2         3            4       5     6        7           8       
    1         2         3            4       5     6        7           8       
    1         2         3            4       5     6        7           8       

2

solved How to add values to existing columns in a text file (using Python)