In this article, we will see how to create a text file in Python. We do not need any external libraries for this, Python provides built-in functions for creating a new text file.
Follow the steps to create a text file:
file = open("new.txt", "w") file.write("This is the new text file created\nPythonpoint") file.close()
We declared the variable
file to open a file named new.txt.
open takes 2 arguments, the file that we want to open and a mode, it is an optional string that specifies the mode in which the file is opened. It defaults to
'r' which means open for reading in text mode.
Here, we used “w” letter in our argument, which indicates write and will create a file if it does not exist in the library.
If you want to perform both read and write operations, you can use w+ instead of w.
write function to enter data into the file.
close function will close the instance of the file created.
The output of the above piece of code will be: