PYTHON PROGRAMMING EXERCISES 5: FILE HANDLING (WRITING TO A FILE)

in STEMGeeks20 days ago

In my last post, I talked about file handling along with simple code that will read characters from your file but in this post I am going to use another mode i.e. write mode. It will allow a text to be written to your file from the python program.

f = open("Written Text.txt", "w")

f. write("This text was written from Python Program.")

f.close()

As of now, there's no such file Written Text.txt in my directory. Executing above program will automatically create a new text file with that name. See below:

image.png

If I run this program, a new file will be created and that content will be written there.

image.png

If you write one more lines f. write("This is write access mode.") to the above code and then run it, you will see the following output.

image.png

Other way to do the same can be done in the following ways.

f = open("Written Text.txt", "w")

content = ["This text was written from Python Program.", "This is write access mode."]

f.writelines(content)

f.close()


If you run your code and check the Written Text.txt file, you will see the same output as above code. To make each sentence appears in new line. You can use \n. For example:

f = open("Written Text.txt", "w")

content = ["This text was written from Python Program.\n", "This is write access mode.\n", "This is File Handling Example."]

f.writelines(content)

f.close()


The output of this code is:

image.png

Sort:  

Thanks for the python posts, they really are useful. I have a quick question, it seems this always appends the text to the end of the file, what if you wanted to override the text that is already there? do you open the file differently? or is it a different command?

I am not appending. I am creating a new text file each time i.e. it will override the existing text. This post is for the same as you say :)