Add spaces to the end of the field - python

1

Hello, everyone.

I have a * .txt file in which there is a column with the product code and another column with the quantity value as below:

Cód.          qtd
7513020087041;5.0

879705341017;24.0

11713777;8.0

17565097;2.0

181420;20.0

181421;20.0

But the system to which I export this file does not accept because the code field needs to be formatted with 13 characters, and if it does not have the 13 characters it needs to be filled with blanks as in the example below:

7513200870410;5.0

879075341017_;24.0

11713777_____;8.0

17565097_____;2.0

181420_______;20.0

181421_______;20.0

Note: Read '_' = '' spaces.

    
asked by anonymous 11.01.2018 / 19:45

1 answer

2

You can use ljust :

print('7513200870410'.ljust(13)) # '7513200870410'
print('181420'.ljust(13)) # '181420       '

Or format (python3.x):

print('{:<13}'.format(7513200870410)) # '7513200870410'
print('{:<13}'.format(181420)) # '181420       '

Example with your data to be recorded later in a file:

dados = '''
    7513020087041;5.0
    879705341017;24.0
    11713777;8.0
    17565097;2.0
    181420;20.0
    181421;20.0
'''

dados_new = ''
for d in dados.split():
    cod, qtd = d.split(';')
    dados_new += '{:<13};{}\n'.format(cod, qtd)

# guardar dados_new em um novo ficheiro:
""" OUTPUT
7513020087041;5.0
879705341017 ;24.0
11713777     ;8.0
17565097     ;2.0
181420       ;20.0
181421       ;20.0
"""

DEMONSTRATION

If you want to write to a file again with everything formatted you can, following the example code above:

...
print('\n'.join('{};{}'.format(x,y) for x,y in dados_new), file=open('new_file.txt', 'w'))

# output:
"""
7513020087041;5.0
879705341017 ;24.0
11713777     ;8.0
17565097     ;2.0
181420       ;20.0
181421       ;20.0
"""

DEMONSTRATION

    
11.01.2018 / 19:51