got it--thanks got it--thanks - 1 year ago 63
Python Question

Tabs in txt file vs terminal

I'm learning Python at the moment and I'm wondering why tabs look a little different in a txt file than when written to the terminal.

In particular, I've run this script

my_file = open('power.txt', 'w')
print( 'N \t\t2**N\t\t3**N' )
print( '---\t\t----\t\t----' )
my_file.write( 'N \t\t2**N\t\t3**N\n' )
my_file.write( '---\t\t----\t\t----\n' )

for N in range(11) :
print( "{:d}\t\t{:d}\t\t{:d}".format(N, pow(2,N), pow(3,N)) )
my_file.write( "{:d}\t\t{:d}\t\t{:d}\n".format(N, pow(2,N), pow(3,N)) )

In it you can see that I'm writing the same thing to both the terminal and the power.txt file. What I see in the terminal is

enter image description here

and what I see in the txt file is

enter image description here

As you can see the third column lines up much nicer in the terminal than the txt file. I've got two questions:

  1. As I'm writing the exact same data to both, why does the information display differently in the txt file?

  2. If I wanted the columns in the txt file to line up like they do in the terminal (to improve readability), how could I alter my script to do so?

Answer Source

Don't rely on tabs, they're application/console dependent. Use str.format instead (format specification)

BTW pow(2,N) is a floating number. You want integral powers: 2**N

Standalone example writing to standard output:

import sys

my_file = sys.stdout
header = "{:<10s}{:<10s}{:<10s}\n".format('N','2**N','3**N' )


for N in range(11) :
    row =  "{:<10d}{:<10d}{:<10d}\n".format(N, 2**N, 3**N)


N         2**N      3**N      
0         1         1         
1         2         3         
2         4         9         
3         8         27        
4         16        81        
5         32        243       
6         64        729       
7         128       2187      
8         256       6561      
9         512       19683     
10        1024      59049     

(you could use legacy C-style format like %20s or %-10s but it's frowned upon now as deprecated, and the format interface is much much more powerful)