Skip to main content
 首页 » 编程设计

python之重复附加到文本文件

2025年05月04日15softidea

我在 python 程序中多次写入同一个文本文件。如何在文本文件末尾写入新内容?也就是说,我需要始终将指针指向“输出”文件的行尾并写入新文本。

我尝试了以下方法,但没有用?

out.seek(0, 1) 

请您参考如下方法:

嗯,这取决于...

  • 如果您不关闭文件并且不在两次写入操作之间移动文件指针(使用 seek),新内容将自动附加到末尾:

    file.write("Hello") 
    file.write("World") 
    
  • 如果您关闭了文件,您可以在"a"(用于追加)模式下重新打开它

    file.write("Hello") 
    file.close() 
     
    file = open("myfile.txt", "a") 
    file.write("World") 
    

    或(如果您使用 context managers ):

    with open("myfile.txt", "w") as file 
        file.write("Hello") 
     
    # implicit close here 
     
    with open("myfile.txt", "a") as file 
        file.write("World") 
    
  • 如果您使用 seek 移动了文件指针,您可以使用 seek(0,2) 定位到末尾(这意味着“末尾为零字节”)

    file.write("Hello") 
    file.seek(here-or-there) 
    file.do_this_or_that 
     
    file.seek(0, 2) 
    file.write("World")