Create file in Python
In this article, we have explained the process of how to Create file in Python. We have used os library.
Table of contents:
- Create file in Python
- Complete Code
Create file in Python
To create file in Python, we use the os library which we need to import.
import os
To create a file, we will use mknod() function of os library.
os.mknod("file.txt")
This will work if the file does not exist. So, one should create a new file only if it does not exist already. We can check if the file exist using os.path.exists() function and take a path accordingly.
if !os.path.exists("file.txt"):
os.mknod("file.txt")
Complete Code
Following is the complete Python code to create file:
import os
if !os.path.exists("file.txt"):
os.mknod("file.txt")
print ("File Created")
else:
print ("File already exists")
With this article at OpenGenus, you must have the complete idea of how to Create file in Python.