How to create a text file in Python
To create a text file in Python you will need to work with file object of Python. To create a text file and to add some text in it we will need to use two inbuilt functions of Python. These functions are open() and write(). With the help of these two functions, we can easily learn how to create a text file in Python and also learn how to add some text to it.
So I hope you have understood that we are not going to import anything in order to create text files in Python, instead of that we will use a built-in object of python.
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 this file 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”
So from this single line, you can easily guess what does this open() function do.
open() in Python – Has two parameters.
- The first parameter will contain the file name you are going to open or create.
- The second parameter is the mode of the file you are going to open or create.
For those who did not understand the second parameter,
The second parameter will contain the mode of the file that means how would you like to open the file.
- If you need to just read a file which is already present in the directory then you can only use “r”
- If you need to write a file already present in the directory you can use “w”
- To append a file use “a”
But if you add a “+” sign to the mode parameter than it will create a file if it does not exist in the directory.
So in this tutorial, we have used w+ as we want to learn how to create text file in Python.
You may also learn,
- How to read a specific line from a text file in Python
- How to count the number of lines in a text file in Python
Add some texts to a text file in Python
To add texts to a text file we can use write() function.
Here is an easy example on How to add 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
Before running the code it will be like:
Now after running this file let’s see how it looks like:
After running the Python Code we can see we have got a newly created text file with some texts in it. The texts we have passed as a parameter in write() method has been added to this newly created text file.
You may also learn,