Home > OS >  Text File doesn't append ("a") after opened in write mode ("w") in Python
Text File doesn't append ("a") after opened in write mode ("w") in Python

Time:11-21

After opening a text file in "w" mode and write something in it; after when i wanna open the same file in append mode (coz i wanna keep the contents on the first line the same) it overwrites the content instead of adding below it.

Below are the sample:

Code:

hand1 = open("test.txt", "w")
hand1.write("Good Morning")
hand1.close()

hand2 = open("test.txt", "a")
hand2.write("\n"   "Hello")
hand2.close()

text file:

Good Morning

Hello

No matter how many times i run this python file, it still gives me the same output which is:

textfile:

Good Morning

Hello

where i expect the output to be (if i run the python file multiple times):

text file:

Good Morning
Hello
Hello
Hello

Anyone knows how to fix this? "Hello" could be in there for multiple lines if the "w" mode isnt opened.

CodePudding user response:

Every time you run the script, you will create a new file that overwrites your old file. You can add an if statement to check if your file already exists, and if not, create one.

import os

if not os.path.isfile("test.txt"): 

    hand1 = open("test.txt", "w")
    hand1.write("Good Morning")
    hand1.close()

hand2 = open("test.txt", "a")
hand2.write("\n"   "Hello")
hand2.close()

CodePudding user response:

From the code it seems you open the file in w mode first and then a mode. So everytime you run this file it will first open it in write mode thereby overwriting the earlier contents. Also when you run the script again it will not just execute append part, but will run the entire script. If you want that behavior you can do this.

  1. Pass an argument as -w to write to the file or -a to append to the file or both -wa to do write and append to the file.
  2. Based on the argument decide on which part of the code to execute.

So possible ways to execute your script can be python test.py -w, python test.py -a, python test.py -wa

  • Related