如何在python的txt文件中沿行的固定位置写文本?

问题描述

在使用python编写txt文件时,例如,我必须在每个句子的末尾加上“]”。我不知道每个句子的长度。但是,我必须确保“]”是该行中的第50个字符。 (句子的长度将小于50)。文件中的文本应如下所示:

Apple       ]
Ball        ]
Cat         ]
Dog         ]
Elephant    ]
Frog        ]

解决方法

类似的东西:

lst = ['Bpple','Apple','Ball','Cat','K','ABCDEFGH']
with open('out.txt','w') as f:
  for word in lst:
    f.write(word.ljust(49) + ']\n')

out.txt

Bpple                                            ]
Apple                                            ]
Ball                                             ]
Cat                                              ]
K                                                ]
ABCDEFGH                                         ]