Search code examples
pythonpadding

Not getting correct format when using ljust in file


I am reading a text file (here is a snippet of the file: https://i.sstatic.net/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.sstatic.net/QkuMo.png

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')