我正在使用Python,并且想在不删除或复制文件的情况下将字符串插入文本文件。我怎样才能做到这一点?
取决于你要做什么。要附加,可以用"a"打开它:
"a"
with open("foo.txt", "a") as f: f.write("new line\n")
如果要先添加某些内容,则必须先从文件中读取:
with open("foo.txt", "r+") as f: old = f.read() # read everything in the file f.seek(0) # rewind f.write("new line\n" + old) # write the new line before