In python open file for writing code, you don't have to import any python module. Basic functionality of python regarding file open for writing or reading is a built in feature. When every in python we want to open a file for writing we have to take care about few important points. First one is in python there are two types of files, First one is text file and all the other files are categorized under name of binary files.
Here we are going to discuss about opening a text file only. There are three modes of opening a file namely
1. r - Read mode. It is used to open file for reading a file only.
2. w - Write mode. This is used when we want to write to a file
3. a - Append mode, when we want to write add data to an existing file with data.
We will use the "w" mode, as we want to write in a file with the help of python. Please keep in mind, if we will open any file with python with write mode or "w", any existing file will be erased and data will be lost. If you want to open and existing file for writing, used append mode only.
There are three steps when we will writing in a text file.
1. Open file for writing
2. Write the piece of text with the help of python syntax
3. Close the file which we opened for writing.
Now, lets see how it works. First see the code in python IDLE, The first step.
If you are related to python, have to deal with it for your tasks, from basics to advanced level, Python Excel, Python and databases, File I/O, Data science, object oriented python etc etc, I would strongly suggest you that you don't miss the opportunity to check Practical Python courses with videos and data here! 1 week Free Trial
#Code for opening a file
Now this python code will open file for writing.
Now write something in the file.
>>>fileobject.write("Explaining Python open file for writing in this tutorial\n");
This code will write the sentence in the file. After writing we will close the file.
Now go to your root directory of python and you will see a text file the given name and this text written in it. You are the proud developer of a text file with the help of python code.