Python Create File

Python Variables

Using Python, you can create files of different types like .txt, .pdf, etc. File handling is an important aspect of a programming language, and while learning a skill, one must learn every part of it to increase the usability of that skill.

You have to open a file before you create it. Sounds confusing, right? Well, it is not if you understand the fact that when you open a file, you specify an access mode.

The access mode is a way of telling Python what you are intending to with the file while it is open.

To create a file, any of these four access modes can be used w, w+, a, a+.

w‘ letter is the access mode to write into the opened file and ‘a‘ is short to append into the opened file.

Create an empty file in Python

We use the with open() method to open the file that we want to create. If you don’t use the write() method, the file that Python creates will be an empty file.

Example

Python Create empty file

with open() method of creating new files in Python will only create a file if it does not exist. The file will be created at the current working directory of your Python script.

Creating a File at specified path

You already know that we pass the name of the new file in the open() function. But, if you want to specify the file location, you can pass the whole path of the file including the file name.

Here’s how you can do that:

Example

Python Create File-input

Let’s check the output of the above code.

Python Create File-output

Create an HTML file in Python

The idea of writing HTML code from Python sounds incredible! HTML code that you write from Python is like data for the language that can be manipulated.

You can create and write into an HTML file as shown below

Example

Python Create HTML File

If you tried this example yourself, you observed that it creates a new HTML file at the specified path.

Tutorials for all brains!