Python os.mknod() Method



Python method mknod() of OS module creates a filesystem node, such as file, device special file and named pipe with the given path.

Its "mode" parameter is used to specify permissions related to the file. However, if we combine it using bitwise OR with one of the given constants stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLK, and stat.S_IFIFO, we can easily control the type of node to be created.

Syntax

Following is the syntax for Python os.mknod() method −

os.mknod(filename, mode, device, *, dir_fd)

Parameters

The Python os.mknod() method accepts five parameters, which are as follows −

  • filename − This is the filesystem node to be created.

  • mode − This parameter specifies both permissions to use and the type of node to be created.

  • device − This parameter indicates the device's special file to be created. Its default value is 0.

  • dir_fd − It represents a file descriptor that refers to a directory.

  • * − It indicates that all following parameters (in this case, dir_fd) are keyword-only parameters.

Return Value

The Python os.mknod() method does not return any value.

Example

The following example shows how to create a filesystem node with read and write permissions using the mknod() method.

import os
import stat

filename = "/home/tp/Python/new/tmpfile"
mode = 0o600|stat.S_IRUSR

# creating filesystem node 
os.mknod(filename, mode)
print("node created")

On running the above program, it will create a simple file in "/home/tp/Python/new" directory with the name "tmpfile" −

node created

Example

In this example, we are creating a character device special file with specified major and minor device numbers.

import os
import stat

# Specify the path and the device type
path = "/home/tp/Python/Tutorials/tmpfile"

# Specify the mode
mode = stat.S_IFCHR | 0o600  
print("Mode specified: ", oct(mode))

# Major and minor device numbers
dev = os.makedev(10, 20)  
print("Device numbers: ", dev)

# Create a character device
os.mknod(path, mode, dev)  
print("Character device created at: ", path)

When we execute the above code, it will display the following output −

Mode specified:  0o20600
Device numbers:  2580
Character device created at:  /home/tp/Python/Tutorials/tmpfile
python_files_io.htm
Advertisements