Home > Enterprise >  Using Python rjust(8) does not seem to work on last item in list
Using Python rjust(8) does not seem to work on last item in list

Time:12-07

I have text file containing comma separated values which read and output again reformatted.

102391,-55.5463,-6.50719,-163.255,2.20855,-2.63099,-7.86673
102392,11.224,-8.15971,15.5387,-11.512,-3.89007,-28.6367
102393,20.5277,-62.3261,-40.9294,-45.5899,-53.222,-1.77512
102394,188.113,19.2829,137.284,14.0548,4.47098,-50.8091
102397,-24.5383,-3.46016,1.74639,2.52063,3.31528,16.2535
102398,-107.719,-102.548,52.1627,-78.4543,-65.2494,-97.8143

I read it using this code:

with open(outfile , 'w') as fout:
    with open(infile) as file:
        for line in file:
            linelist = line.split(",")
            fout.write("            ELEM  "   '{:>8}'.format(str(linelist[0])   "\n"))
            if len(linelist) == 7:
                fout.write("           VALUE   "   str(linelist[1][:8]).rjust(8)   str(linelist[2][:8]).rjust(8)   str(linelist[3][:8]).rjust(8)   str(linelist[4][:8]).rjust(8)   str(linelist[5][:8]).rjust(8)   str(linelist[6][:8]).rjust(8) ) 
                fout.write("\n")

And get this output:

    ELEM   102391
   VALUE   -55.5463-6.50719-163.255 2.20855-2.63099-7.86673
    ELEM   102392
   VALUE     11.224-8.15971 15.5387 -11.512-3.89007-28.6367
    ELEM   102393
   VALUE    20.5277-62.3261-40.9294-45.5899 -53.222-1.77512
    ELEM   102394
   VALUE    188.113 19.2829 137.284 14.0548 4.47098-50.8091
    ELEM   102397
   VALUE   -24.5383-3.46016 1.74639 2.52063 3.3152816.2535

    ELEM   102398
   VALUE   -107.719-102.548 52.1627-78.4543-65.2494-97.8143

Everything is fine except: Why do I get a extra blank line sometimes, and why is the last number before the blank line (16.2535) not rightadjusted? These two issues certainly belong to each other but i can not figure out what is going on.

CodePudding user response:

It behaves like the last element of the fifth line of your input contins a 'newline' character at its end.

Can you check the content of linelist[6] for the fifth line of your input? I guess you would find something like: '16.2535\n'.

Hence,to make sure that your content does not include trailing newlines at the end of the string, you can use the String function .strip()

  • Related