Align columns in a text file

前端 未结 3 1406
北海茫月
北海茫月 2021-02-05 10:03

I am a Python noobie and I\'m stuck on something I know is going to be simple...

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

dtrapani  HCPD-E         


        
3条回答
  •  有刺的猬
    2021-02-05 10:53

    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)
    

提交回复
热议问题