0

I want to append spaces at the end of line if line does not have 80 characters in Python. I have referred How can I fill out a Python string with spaces? from StackOverflow. Please find input and output as below. Could you please advise me to change any code? Thank you.

What I have tried?

I have written the following code:

#!/usr/bin/env python

import sys

input_file = open(sys.argv[1],'r')
lines = input_file.readlines()
sys.stdout = open(sys.argv[2],'w')

for line in lines:
    if len(line) != 80:
        print(line.ljust(80, ' '))
    else:
          print(line[0:80])

sys.stdout.close()

input_file.txt

01010001ADPBI001PEACH   ADP6619200508215754
01010002SCOBIADPADPPW06 200508215754                ADP4
01065008200511P6206  T YS2020050720200511COMO 4005181997      BLTF0510002

expected_output_file.txt

01010001ADPBI001PEACH   ADP6619200508215754                                     
01010002SCOBIADPADPPW06 200508215754                ADP4                        
01065008200511P6206  T YS2020050720200511COMO 4005181997      BLTF0510002       

As per above program, I am getting the below output:

01010001ADPBI001PEACH   ADP6619200508215754

01010002SCOBIADPADPPW06 200508215754                ADP4

01065008200511P6206  T YS2020050720200511COMO 4005181997      BLTF0510002
Jayveer Parmar
  • 500
  • 7
  • 25

1 Answers1

0

You can use the F-String interpolation and the format specification mini-language, specifically the "align" < operator.

So, for each line you would do:

line = '01010002SCOBIADPADPPW06 200508215754                ADP4'
space_filled = f'{line:<80}'

space_filled will output:

'01010002SCOBIADPADPPW06 200508215754                ADP4                        '

For Python <= 3.5 you won't be able to use F-String, since they were introduced in Python 3.6. You can still use other string interpolation methods, such as:

space_filled = '{:<80}'.format(line)

Also, please note that when you do lines = input_file.readlines(), the list lines will contain the strings for each line of the file, but with a trailing new-line character (\n) included. So, when you do the space filling, you are actually appending them in a line below of each line of the original file.

To get rid of this, just update that part of your code, using the splitlines() method of the str class (and don't forget to close it ;-) ):

lines = input_file.read().splitlines()
input_file.close()

The entire script should look as follows:

import sys

input_file = open(sys.argv[1],'r')
lines = input_file.read().splitlines()
input_file.close()
sys.stdout = open(sys.argv[2],'w')

for line in lines:
    print('{:<80}'.format(line))

sys.stdout.close()
revliscano
  • 2,227
  • 2
  • 12
  • 21