本文介绍了写入文本文件的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让程序在运行时自动从文本文件的最后一行开始并使其写入最后一行.我目前的代码如下:
I am trying to get the program to automatically start at the last line of a text file when I run it and make it write on the last line. My current code is as follows:
with open('textfile.txt', 'a+') as tf
last_line = tf.readlines()[-1]
tf.write(linetext + '\n')`
当我运行它时,它说列表索引超出范围.如何让它自动跳到文本文件的最后一行并从那里开始写作?
When I run this, it says that the list index is out of range. How do I get this to automatically skip to the last line of a text file and start writing from there?
推荐答案
打开文件时使用 a
标志
Use the a
flag while opening the file
with open('path/to/file', 'a') as outfile:
outfile.write("This is the new last line\n")
这篇关于写入文本文件的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!