你无法直接在文件开头插入数据。必须全部读出来,插入,重新写入
with open("path_to_file", "r") as f:
contents = f.readlines()
contents.insert(index, value)
with open("path_to_file", "w") as f:
contents = "".join(contents)
f.write(contents)
不要用 open(“”, “a”),a会让打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。
用open(“”,“r+”),打开一个文件用于读写。文件指针将会放在文件的开头。
f=open("1.txt","a")
f.write("你好")
f.close()
望采纳