如何写入 Python 中文本文件的精确右侧?

How to write to exact right of text file in Python?

所以我有一个代码,我需要在其中写入类似这样的文件。

def f():
       f.write(anothervar)
       f.write("\t \t \t \t <------------------ Written from function f ")
       f.write('\n')
def g
f():
       f.write(somevar)
       f.write("\t \t \t \t <------------------ Written from function g ")
       f.write('\n')

然而,当显示文本文件时,它看起来像这样(代码被截断)

HELLO WORLD           <------------------ Written from function g
HELLO WORLD MORE BIG BIGGER           <------------------ Written from function f
HELLO WORLD BIGGEST HAHAHAHAHAHAHAHAHHA          <------------------ Written from function f

我希望每个 <--- written from function g/h 都写得完全正确。我怎样才能做到这一点?根据我的想法,我可以在写完 hello world 后测量每行的长度,然后减去并进行数学运算,但这看起来很难,而且我不知道有任何函数可以按行测量 chr。我需要简短的代码。

可以通过获取字符串长度来获取space插入多少,或者使用srt.rjust.

def adjust(string, function):
    left, right = 20, 40
    tag = '<'+'-'*(15-len(function))+' write from function ' + function
    print(string.ljust(left, ' ') + tag.rjust(right, ' '))

text = ['Good Morning !', 'Are you ready', 'How about', 'Test']
func = ['get', 'get', 'post', 'delete']
for t, f in zip(text, func):
    adjust(t, f)
Good Morning !         <------------ write from function get
Are you ready          <------------ write from function get
How about              <----------- write from function post
Test                   <--------- write from function delete

使用 format() 可以调整插入文本的长度

w1 = "This is some text"
w2 = "This is longer text"
w3 = "this is an even longer text "

f.writelines("{:<40} - <----------- Written from w1\n".format(w1))
f.writelines("{:<40} - <----------- Written from w2\n".format(w2))
f.writelines("{:<40} - <----------- Written from w3\n".format(w3))

This is some text                        - <----------- Written from w1
This is longer text                      - <----------- Written from w2
This is an even longer text              - <----------- Written from w3