Python 3 – os.mknod() Method
The os.mknod()
method is used to create a special file like a character device, block device or named pipe. This method creates a filesystem node with the name pathname
.
Syntax
The syntax of the os.mknod()
method is:
os.mknod(path[, mode=0o600, device_type=0])
Parameters
The os.mknod()
method takes the following parameters:
path
– this is the path of the file to be created.mode
(optional) – this specifies the permission mode of the file to be created. Default is 0o600 (read and write permission for the owner of the file).device_type
(optional) – this specifies the type of device to create. The default is 0 (a regular file). The other options arestat.S_IFIFO
(a named pipe or FIFO),stat.S_IFCHR
(a character device), andstat.S_IFBLK
(a block device).
Return Value
The os.mknod()
method doesn’t return any values.
Example
The following example demonstrates the usage of the os.mknod()
method. The following code creates a character device file named testchardev
with a permission mode of 0o666.
import os
# creating character device file
os.mknod("testchardev", 0o666, stat.S_IFCHR)
Explanation
In the example above, we’ve imported the os
module and called the mknod()
method to create a character device file "testchardev"
with permission mode of 0o666
using stat.S_IFCHR
from stat
module, which creates the file type character device.
We can confirm the file has been created by using the os.path.exists()
method:
import os
if os.path.exists("testchardev"):
print("File exists")
This code will output File exists
.
Conclusion
In summary, the os.mknod()
method is used to create special files such as character devices, block devices or named pipes. The method takes the path
, mode
, and device_type
as inputs to create the file. We can use the os.path.exists()
method to verify the creation of the file.