Nilani Algiriyage
Nilani Algiriyage

Reputation: 35666

Append to text file repeatedly

I'm writing to the same text file multiple times during a python program. How to write new contents at the end of text file? That is I need always to place the pointer to the end of lines of the "out" file and write the new text.

I have tried the following, which didn't work?

out.seek(0, 1)

Upvotes: 1

Views: 2442

Answers (2)

Sylvain Leroux
Sylvain Leroux

Reputation: 52000

Well, it depends...

  • If you don't close the file and don't move the file pointer (using seek) between two write operations, new content is appended automaticcaly at the end:

    file.write("Hello")
    file.write("World")
    
  • If you have closed your file, you could re-open it in "a" (for append) mode

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

    or (if you use 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")
    
  • If you have moved the file pointer using seek , you could position at the end using seek(0,2) (this mean "zero bytes from the end")

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

Upvotes: 6

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Open the file in append mode:

open(filename, 'a')

From docs :

'a' opens the file for appending; any data written to the file is automatically added to the end.

Upvotes: 1

Related Questions