Python File Create

python-file-create-youtube-ipcisco

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:

 

  • r” To read the file. Returns error if there is no such a file.
  • a” To open the file to append to the end of the file. If there is no file, it creates.
  • w” To open the file to write and overwrite. If there is no file, it creates.
  • x” To create the file. Returns error if there is such a file.

 

pyhthon-open-function-file-operation-modes

 

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.

 

a = open("Ourfile.txt", "x")

 

how-to-create-files-with-python-ipcisco-2

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:

a = open("Ourfile.txt", "w")
a.write("I like creating files!")
a.close()

 

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:

 

a = open("Ourfile.txt", "r")
print(x.read())

 

I like creating files!

 

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!

 

Back to: Python Programming Course > Python File Handling

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts