In the previous lessons of Python Course, we have worked with existing files. Firstly, we have learned how to read an existing file with Python File Read lesson, then, we have learned how to modify an existing file with Python File Write lesson. Now, we will focus Python File Create and we will learn how to create files in python.
To create a file in python, we will use python open() function again. AS we have discussed before, there are two different parameters of open method. The first one is file name and the second one is mode. These modes are given below:
Here, for Python File Create function, we will use “x” parameter as the second parameter. The first parameter will be the name of the file that we will create.
Below, you will find an example that we will create a file named Ourfile.txt. Here, we will use Ourfile.txt as the fisrt and “x” as the second parameter of open function.
After this File Create code, a new file has created. It is empty now. To fill the content of this file, we can use write mode with open function like below:
After that, when we read the content of this file with the help of open function and read method, we will see the below output as we have filled the content:
This is basically, how to create a file in python. Here, we have learned, Python File Create methods with an example. You will use these methods in the future too much in your python file handling activities.
You can also watch the video of this lesson!