我想做的是:
with open(textfile, 'at') as f:
f.write(f'{current_line_number}: ' + "Some text" + '\n')
最佳答案
您可以使用'r+'(读写模式)打开文件,然后您可以使用readlines()
获取行列表并计算列表有多少行len()
,然后只需在结果中添加+1:len(f.readlines()) + 1
,您就可以得到文件有多少行。像这样的事情:
with open(textfile, 'r+') as f:
current_line_number = len(f.readlines()) + 1
f.write(f'{current_line_number}: ' + "Some text" + '\n')
关于python - 如果我以附加模式打开文本文件,我可以找出我所在的行号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75664281/