Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not getting correct format when using ljust in file

I am reading a text file (here is a snippet of the file: https://i.stack.imgur.com/O2c84.png) and my aim is to make all the words the same length (need to be 16 characters) by padding them with " * " (eg abcd*********) and write them to a new file.

What I’ve done below is

padding = '*'
len = 16

with open("WordList.txt", "r") as input:
     with open("NewWordList.txt", "w") as output:
        for x in input:
            x = x.ljust(len, padding)
            output.write(x)

When I open the newly created file, the padding is going onto another separate line, see the link -> https://i.stack.imgur.com/QkuMo.png

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone help me understand what is going wrong? I am still new at Python. Thanks.

>Solution :

Each line in your original text file ends with a newline character. You need to strip that off, then ljust, just append a newline. Otherwise, the padding gets added after the newline, which is what you are seeing.

padding = '*'
len = 16

with open("WordList.txt", "r") as input:
     with open("NewWordList.txt", "w") as output:
        for x in input:
            x = x.strip().ljust(len, padding)
            output.write(x + '\n')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading