Home > Blockchain >  left padding with python
left padding with python

Time:10-25

I have following data and link combination of 100000 entries

dn:id=2150fccc-beb8-42f8-b201-182a6bf5ddfe,ou=test,dc=com
link:545214569

dn:id=ffa55959-457d-49e6-b4cf-a34eff8bbfb7,ou=test,dc=com
link:32546897

dn:id=3452a4c3-b768-43f5-8f1e-d33c14787b9b,ou=test,dc=com
link:6547896541

I am trying to write a program in python 2.7 to add left padding zeros if value of link is less than 10 .

Eg:

545214569  --> 0545214569
32546897   --> 0032546897

can you please guide me what am i doing wrong with the following program :

    with open("test.txt", "r") as f:
     line=f.readline()
     line1=f.readline()
     wordcheck = "link"
     wordcheck1= "dn"
     for wordcheck1 in line1:
         with open("pad-link.txt", "a") as ff:
             for wordcheck in line:
                 with open("pad-link.txt", "a") as ff:
                     key, val = line.strip().split(":")
                     val1  = val.strip().rjust(10,'0')
                     line = line.replace(val,val1)
                     print (line)
                     print (line1)
                     ff.write(line1   "\n")
                     ff.write('%s:%s \n' % (key, val1))

CodePudding user response:

The usual pythonic way to pad values in Python is by using string formatting and the Format Specification Mini Language

link = 545214569
print('{:0>10}'.format(link))

CodePudding user response:

Your for wordcheck1 in line1: and for workcheck in line: aren't doing what you think. They iterate one character at a time over the lines and assign that character to the workcheck variable.

If you only want to change the input file to have leading zeroes, this can be simplified as:

import re

# Read the whole file into memory
with open('input.txt') as f:
    data = f.read()

# Replace all instances of "link:<digits>", passing the digits to a function that
# formats the replacement as a width-10 field, right-justified with zeros as padding.
data = re.sub(r'link:(\d )', lambda m: 'link:{:0>10}'.format(m.group(1)), data)

with open('output.txt','w') as f:
    f.write(data)

output.txt:

dn:id=2150fccc-beb8-42f8-b201-182a6bf5ddfe,ou=test,dc=com
link:0545214569

dn:id=ffa55959-457d-49e6-b4cf-a34eff8bbfb7,ou=test,dc=com
link:0032546897

dn:id=3452a4c3-b768-43f5-8f1e-d33c14787b9b,ou=test,dc=com
link:6547896541

CodePudding user response:

i don't know why you have to open many times. Anyway, open 1 time, then for each line, split by :. the last element in list is the number. Then you know what lenght the digits should consistently b, say 150, then use zfill to padd the 0. then put the lines back by using join

for line in f.readlines():
  words = line.split(':')
  zeros = 150-len(words[-1])
  words[-1] = words[-1].zfill(zeros)
  newline = ':'.join(words)
  # write this line to file 
  • Related