Skip to content Skip to sidebar Skip to footer

Wrong Format Of Generated Text File In Python

I have a big parent list containing many lists of tuples like the small example: [ [('id', 'name', 'Trans'), ('ENS001', 'EGSB', 'TTP')], [('id', 'name', 'Trans'), ('EN02', 'EHGT'

Solution 1:

You are writing it all on one line, you need to add a newline:

rows = (sub[1] forsubin z)


with open('out.txt','w') as f:
    f.write ("{}\n".format(' '.join(z[0][0]))) # add a newline
    for i in rows:
        f.write ("{}\n".format(' '.join(i))) # newline again

If you always have three elements in your rows and you want them aligned:

rows = [sub[1] forsubin z]


mx_len = 0for tup in rows:
    mx = len(max(tup[:-1],key=len))
    if mx > mx_len:
        mx_len = mx

with open('out.txt', 'w') as f:
    a, b, c = z[0][0]
    f.write("{:<{mx_len}} {:<{mx_len}} {}\n".format(a, b, c, mx_len=mx_len))
    for a, b, c in rows:
        f.write("{:<{mx_len}} {:<{mx_len}} {}\n".format(a, b, c, mx_len=mx_len))

Output:

id     name   Trans
ENS001 EGSB   TTP
EN02   EHGT   GFT

If the length varies:

with open('out.txt', 'w') as f:
    f.write(("{:<{mx_len}}"*len(z[0][0])).format(*z[0][0], mx_len=mx_len) + "\n")
    for row in rows:
        f.write(("{:<{mx_len}}"*len(row)).format(*row, mx_len=mx_len) + "\n")

Solution 2:

If you want to align column with spaces, first you have to determine what each column's width will be -- presumably the length of the longer header or content of each column, e.g:

wids = [len(h) for h in z[0][0]]
for i in rows:
    wids = [max(len(r), w) for w, r inzip(wids, i)]

Then on this basis you can prepare a format string, such as

fmt = ' '.join('%%%ds' % w for w in wids) + '\n'

and finally, you can write things out:

with open('out.txt','w') as f:
    f.write(fmt % z[0][0])
    for i in rows:
        f.write(fmt % i)

Solution 3:

If you want the output to be separated by tabs like this you can join on \t, rather than ' ', which you are using. The bottom line of your code would look like f.write('\t'.join(i)).

Post a Comment for "Wrong Format Of Generated Text File In Python"