×

Search anything:

OS module (Operating System) in Python

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

The os module provides miscellaneous operating system interfaces that enables us to use the operating system dependent functionality in a portable way. This module provides us a lot of functionalities to get details about the processes,files and directories and make changes to them.

The different methods available in the os module of Python are:

  • getcwd()
  • chdir()
  • listdir()
  • mkdir()
  • rmdir()
  • chmod()
  • os.chown()
  • mknod()
  • stat()
  • open()
  • close()
  • read()
  • write()
  • rename()

We will now go into the details of each method.

getcwd()

This functions is used to get the current working directory.

Syntax: getcwd()
parameter : None
Return Value : This functions return a string value which represents the current working directory of the process/program in which the function is used.

Example :

import os
#crwd:current working directory
cpath=os.getcwd()
print("Current working directory:",cpath)

chdir()

Now that we have learned how to get our present working directory let's try changing our working directory by using the chdir() function.We need to pass a string that contains a valid path in the function to change the directory.

Syntax:chdir(path)

Parameter :

  • path: A string containing a valid path.

Return type: No return value

Example:

import os
print(os.getcwd()) #To print current working directory before change.
os.chdir("your desired path here")
print(os.getcwd()) #To print the current directory after change.

listdir()

We can check the list of the entries(filer,directories etc) present in the given path directory.

Syntax :listdir(path=" ")

Parameter:

  • path :The path parameter contains a string that represent the path of the directory , use path='.' to get the list from the present directory.

Return type :A list of names of entries of the target directory.

Example:

import os
lst=os.listdir(path='.')
#print list of entries of current directories.
for l in lst :
	print(l)

mkdir()

We can also create directories by using the mkdir function.

Syntax: mkdir(path,mode)

Parameters :

  • path : This contain the path where we want to create the directory or just the name if we want to create the directory in the current working directory.
  • mode : This specifies the mode of the directory that we want to create.(use mode=0o777 to set it to numeric mode or this field can be left empty as given in example.)

Return Type : No return type.

Example:

import os
os.mkdir(path)
lst=os.listdir(path='.')
for l in lst :
	print(l) #To print the list of  entries in the current directory.

rmdir()

After creating we can also delete that directory or any other directory using the rmdir() function

Syntax: rmdir(path)

Parameter :

  • path: This parameter contains a string which represents the path of the directory to be deleted or just the name of the directory if it is present in the current working directory.

Return type: No return value

Example:

import os
os.rmdir(path="path to your directory")
lst=os.listdir(path='.')
for l in lst :
	print(l)

chmod()

When working with files there might be cases when you want to changes the modes of the files like readable,writable and executable.We can use the chmod() function to change the mode of the files.the mode of the files can take any of the values given below or a combination of these values which is obtained by performing a bitwise OR on them.

  • stat.S_ISUID − Set user ID on execution.

  • stat.S_ISGID − Set group ID on execution.

  • stat.S_ENFMT − Record locking enforced.

  • stat.S_ISVTX − Save text image after execution.

  • stat.S_IREAD − Read by owner.

  • stat.S_IWRITE − Write by owner.

  • stat.S_IEXEC − Execute by owner.

  • stat.S_IRWXU − Read, write, and execute by owner.

  • stat.S_IRUSR − Read by owner.

  • stat.S_IWUSR − Write by owner.

  • stat.S_IXUSR − Execute by owner.

  • stat.S_IRWXG − Read, write, and execute by group.

  • stat.S_IRGRP − Read by group.

  • stat.S_IWGRP − Write by group.

  • stat.S_IXGRP − Execute by group.

  • stat.S_IRWXO − Read, write, and execute by others.

  • stat.S_IROTH − Read by others.

  • stat.S_IWOTH − Write by others.

  • stat.S_IXOTH − Execute by others.

NOTE: In order to use the above modes in your python program you need to import the stat module as shown in the example below.

Syntax: chmod(path,mode)

Parameters:

  • path : This parameter contains a string which represents a path to the target file or it's name if it is in the current directory.

  • mode: This parameter can have any of the mode mentioned above or their combination.

Return type: No return value

Example:

import os,stat
#To set afile to be executed by the owner only.
os.chmod(path,stat.S_IEXEC)
print("The file mode has been changed.")

os.chown()

We can also change the ownership of a file by using the chown() function.It allows us to change the ownership of the file and the group to which the files belong.
Note: This functionality is available in unix only as we have the concept of owner and groups in Unix.

Syntax: chown(path,uid,gid)

Parameters:

  • path :This parameter contains a string which represents a path to the target file or it's name if it is in the current directory.

  • uid : This parameter contains the userid to which the ownership is to be transfered.

  • gid : This parameter contains the groupid to which the ownership is to be transfered.

Return type: No return value.

Note: If you you want to keep the user or group ownership unchanged pass -1 as the value for that parameter.

Example:

import os
#To change both the user and group ownership of the file.
#The uid and gid used in this example are assumptions replace them with a valid input.
os.chown(path,67,14)

#To change only the user ownership and not the group ownership of a file
os.chown(path,77,-1)

print("Ownership of the file has been changed.")

mknod()

This function is used to create a file system like a file,pipe or a special device file.

Syntax:mknod(filename,[,mode[,device]])

Parameters:

  • filename: This parameter contains the name of the file,pipe or special device file that is to be created.
  • mode : This parameter defines the mode of the file that will be created.The mode are the same which we use in chmod function.
  • device :This is the device special file created and its optional to provide.

Return type: Does not return any value.

Example:

import os
import stat
filename="your filename"
mode=stat.S_IRWXU
os.mknod(filename,mode)
lst=os.listdir(path='.')
for l in lst :
	print(l)

stat()

This function is used to get the status of the given path.

Syntax: stat(path)

Parameter:

  • path : a string containing a valid path to a file.

Return type : This function returns an object os stat_result of the class os.stat_result representing the status of the file.The returned object has the following attributes:

  • st_mode: It represents file type and file mode bits (permissions).
  • st_ino: It represents the inode number on Unix and the file index on Windows platform.
  • st_dev: It represents the identifier of the device on which this file resides.
  • st_nlink: It represents the number of hard links.
  • st_uid: It represents the user identifier of the file owner.
  • st_gid: It represents the group identifier of the file owner.
  • st_size: It represents the size of the file in bytes.
  • st_atime: It represents the time of most recent access. It is expressed in seconds.
  • st_mtime: It represents the time of most recent content modification. It is expressed in seconds.
  • st_ctime: It represents the time of most recent metadata change on Unix and creation time on Windows. It is expressed in seconds.
  • st_atime_ns: It is same as st_atime but the time is expressed in nanoseconds as an integer.
  • st_mtime_ns: It is same as st_mtime but the time is expressed in nanoseconds as an integer.
  • st_ctime_ns: It is same as st_ctime but the time is expressed in nanoseconds as an integer.
  • st_blocks: It represents the number of 512-byte blocks allocated for file.
  • st_rdev: It represents the type of device, if an inode device.
  • st_flags: It represents the user defined flags for file.

Example:

imort os
path="D:\\trial.txt"
status=os.stat(path)
print(status)

Output:
stat

File handling using os module

We can use the functions provided by the os module to work with files and using a file descriptor to access the files.Let's start by learning what a file descriptor is.

File descriptor:File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth.

These are some functions to work with files:

open()

This function is used to open a file and set the requires flags and modes of the file.the default mode is 0o777(octal)

Syntax: open(file,flag[,mode])

Parameters:

  • file :This parameter stores the path to a file or the name of the file.
  • flag :This parameter is used to set a flag for the file.
  • mode :This parameter allows the user to set and change the mode of a file.

Return type : No return value

List of flags:

  • os.O_RDONLY − open for reading only

  • os.O_WRONLY − open for writing only

  • os.O_RDWR − open for reading and writing

  • os.O_NONBLOCK − do not block on open

  • os.O_APPEND − append on each write

  • os.O_CREAT − create file if it does not exist

  • os.O_TRUNC − truncate size to 0

  • os.O_EXCL − error if create and file exists

  • os.O_SHLOCK − atomically obtain a shared lock

  • os.O_EXLOCK − atomically obtain an exclusive lock

  • os.O_DIRECT − eliminate or reduce cache effects

  • os.O_FSYNC − synchronous writes

  • os.O_NOFOLLOW − do not follow symlinks

close()

This function is used to close the file descriptor.

Syntax: close(fd)

Parameter:

  • fd : fd denotes the file descriptor that was created using the open function.

Return type: No return value.

read()

Now that we have created a file descriptor we can use the read function to read the data stored in the file.

Syntax:read(fd,n)

Parameter:

  • fd : fd represents the file descriptor created using the open function.
  • n : n is a integer value which defines the maximum bytes the function should read from the file descriptor fd.

Return type: This functions returns a bytestring containing the bytes read.

Example:

imort os
file="Your file path or file name"
#creating a file descriptor with read only flag.
fd=os.open(file,os.O_RDONLY)
n="Th e number of bytes you wan to read."
#Note: the value of n should be a number.
filetext=os.read(fd,n)
print(filetext)
os.close(fd)

write()

Apart from reading from a file descriptor we can also write into it using the write function.

Syntax:write(fd,text)

Parameter:

  • fd: fd represents the file descriptor.
  • text: It contains the text that is to be written in the file descriptor.

Return type: It returns the number of bytes written in the file descriptor.

Example:

import os
file="Your file path or file name."
#Creating file descriptor in read and write mode.
fd=os.open(file,os.O_RDWR)
text="Your text here"
#Converting text to bytes
fileadd=str.encode(text)
num=os.write(fd,fileadd)
print(num," bytes are added to the file")
os.close(fd)

rename()

This function is used to rename a file using the file descriptor.

Syntax(): rename(fd,name)

Parameter:

  • fd: fd represents file descriptor
  • name : It contains the new name for the file.

Return type: It does not return any value.

Example:

import os
file="Your file path/name"
fd=os.open(file,os.O_RDONLY)
name="Hello.txt"
os.rename(fd,name)
os.close(fd)

These are some of the basic functionalities provided by the python os module to learn more about the os module you can check out the python documentation. With this article at OpenGenus, you must have a good understanding of using os module in your Python projects. Enjoy.

OS module (Operating System) in Python
Share this