pythontext

Padding to a specific level and adding character at the end


I have a text file:

a
aaa
aaa
a

My desired outcome is:

a                               N
aaa                             N
aaa                             N
a                               N

I wrote the following:

newf=""
with open('testfile.txt','r') as f:
   for line in f:
     if len(line) < 87:
         newf+=line.strip()+" "
     else:
        newf+=line.strip()+"N\n"
   f.close()
with open('testfile.txt','w') as f:
  f.write(newf)
  f.close()

When I run this, my outcome becomes:

a aaa aaa a

I can't figure out why it changes the output to one line.


Solution

  • You can consider f-strings to help you do the formatting.

    def reformat_file(filename, desired_length=87, suffix='N'):
        lines = []
        with open(filename, 'r') as fp:
            for line in fp:
                line = line.strip()
                formatted = line
                if len(line) < desired_length:
                    formatted = f"{line:{desired_length}}{suffix}"
    
                lines.append(formatted)
    
        with open(filename, 'w') as fp:
            fp.write('\n'.join(lines))
    
        return
    
    if __name__ == "__main__":
        reformat_file("testfile.txt")
    

    Running reformat_file where testfile.txt contains the below

    a
    aaa
    aaa
    a
    a really long line that will have more than the threshold number of characters is written here.
    abc
    

    Will rewrite overwrite testfile.txt with the following.

    a                                                                                      N
    aaa                                                                                    N
    aaa                                                                                    N
    a                                                                                      N
    a really long line that will have more than the threshold number of characters is written here.
    abc                                                                                    N