我正在自学编程,今天的挑战是编写一个可以将文本左对齐、右对齐或居中对齐的程序。我的主要问题是,一旦打开文件,我不确定如何写入特定行。是否有捷径可寻?这就是我所拥有的。我想我需要以某种方式计算行中的字节,以便我可以 f.seek 到行尾。我觉得 python 已经在某个地方拥有这种类型的功能,但我在网上搜索时找不到它。有什么建议么?
def align():
name= input('what is the name of your txt file?: ')
try:
f=open(name + '.txt','r+')
lines =f.readlines()
just = input('left, right, or centre?: ')
for i in range[,lines]:
j = lines[i].strip('\n')
if just == 'right':
f.seek() #I want it to seek each line but can't figure out what variable might go here...
f.write('{:>30}'.format(line.strip()))
elif just == 'left':
f.seek() #I want it to seek each line but can't figure out what variable might go here...
f.write('{:<30}'.format(line.strip()))
f.seek() #I want it to seek each line but can't figure out what variable might go here...
elif just == 'centre' or just == 'center':
f.write('{:^30}'.format(line.strip()))
else:
print("You didn't choose a justification!")
f.close()