Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align columns in a text file

I have a plain text file that contains user login data:

dtrapani  HCPD-EPD-3687  Mon  05/13/2013    9:47:01.72
dlibby  HCPD-COS-4611  Mon  05/13/2013    9:49:34.55
lmurdoch  HCPD-SDDEB-3736  Mon  05/13/2013    9:50:38.48
lpatrick  HCPD-WIN7-015  Mon  05/13/2013    9:57:44.57
mlay  HCPD-WAR-3744  Mon  05/13/2013  10:00:07.94
eyoung  HCPD-NLCC-0645  Mon  05/13/2013  10:03:01.83

I'm trying to print the data in left- and right-aligned columns:

dtrapani  HCPD-EPD-3687    Mon  05/13/2013    9:47:01.72
dlibby    HCPD-COS-4611    Mon  05/13/2013    9:49:34.55
lmurdoch  HCPD-SDDEB-3736  Mon  05/13/2013    9:50:38.48
lpatrick  HCPD-WIN7-015    Mon  05/13/2013    9:57:44.57
mlay      HCPD-WAR-3744    Mon  05/13/2013   10:00:07.94
eyoung    HCPD-NLCC-0645   Mon  05/13/2013   10:03:01.83

How can I do this?

This is the code I have so far:

with open(r'C:\path\to\logons.txt', 'r') as f:
    for line in f:
        data = line.strip()
        print(data)
like image 287
cstafford Avatar asked May 28 '13 16:05

cstafford


1 Answers

I would go for the new(er) print formatter with this one (assuming your fields are consistent). The print/format statement is pretty easy to use and can be found here. Since your data can be seen as a list, you can do a single call to format and supplying the correct formatter data you'll get your output. This has a bit more fine grained control than ljust or rjust but has the downside that you need to know that your data coming in is consistent.

with open(r'C:\path\to\logons.txt', 'r') as f:
    for line in f:
        data = line.split()    # Splits on whitespace
        print '{0[0]:<15}{0[1]:<15}{0[2]:<5}{0[3]:<15}{0[4]:>15}'.format(data)
like image 168
Jeff Langemeier Avatar answered Sep 22 '22 11:09

Jeff Langemeier