To create a text file in python you will need to work with the file object. In order to create a text file and add some text content in this file, you will need to use two inbuilt functions of Python. these are open( ) and write( ). With the help of these two functions only, it is possible to learn how to create a text file in Python and also it helps to figure out how to add some text content to the file.
So i hope you have understood that we are going to import anything in order to create text files in Python, instead of that we will use a built-in object of Python. That means there are no modules needed to be used for this task.
Create a text file in Python
A single line of code is enough to create a text file:
my_file = open("this_is_file.txt","w+")
If you run the above Python program, it will create a text file in the same directory where this file (the file you have run) is located.
The file name of the newly created text file will be, this_is_file.txt. The open( ) function actually tries to open the file. But we have passed the w+ parameter in the function.
The + is telling the Python interpreter to open the text file with read and write permissions.
The w telling if the file doesn’t exist, then the function will create a new file with the filename we have provided. So it is responsible for creating our new file.
As you have seen, from a single line of code easily guess what this open() function does.
open() in Python – Has two parameters.
- The first parameter will contain the file name you are going to open or create. In our case it is this_is_file.txt.
- The second parameter is the mode of the file you are going to open or create. In our case, it is w+.
Add some texts to a text file in Python
To add texts to a file we can use Python write( ) function.
Here is an easy example of how we can add some text to a text file in Python.
my_file = open("this_is_file.txt","w+") my_file.write("Hey This text is going to be added to the text file yipeee!!!")
If you run this file. It will add the text “Hey This text is going to be added to the text file yipeee!!!” to the text file: this_is_file.txt