Home > Software design >  Why does the function append the txt file and not overwrite when the opening mode is "w'?
Why does the function append the txt file and not overwrite when the opening mode is "w'?

Time:06-13

I was following a tutorial that creates a function to create 20 txt files and add the multiplication tables from 1 to 20 in them. Here is the code-

#Create tables from 1 to 20 in different files 

for i in range(1,21):
    with open(f"table_{i}.txt","w") as f:
        for j in range(1,11):
            f.write(f"{i} x {j} = {i*j}\n")

This code does the job but I am not sure why does it append to the file and not overwrite it when it is open in "w"/writing mode?

CodePudding user response:

Yes, you are right when you use 'w' then it overwrites and does not append but here it is not appending.
The concept of appending and overwriting comes into play when you open the file again but here we are not opening the file again but just writing in the opened file.
Let me explain by an example:

for i in range(1,21):
    for j in range(1,11):
        with open(f"table_{i}.txt","w") as f:
            f.write(f"{i} x {j} = {i*j}\n")

try to run this code, it will give you 20 files as before but this time every file just had just a single column say 10 x 10 = 100 like this only because here we are opening the file after every line so every time we open, 'w' overwrites the old data.

Hope it helps:)

  • Related