Javatpoint Logo
Javatpoint Logo

Python OS Module

The python OS module provides functions used for interacting with the operating system and also get related information about it. The OS comes under Python's standard utility modules. This module offers a portable way of using operating system dependent functionality.

The python OS module lets us work with the files and directories.

There are some functions in the OS module which are given below:

os.name

This function provides the name of the operating system module that it imports.

Currently, it registers 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.

Example

Output:

posix

os.getcwd()

It returns the Current Working Directory(CWD) of the file.

Example

Output:

C:\Users\Python\Desktop\ModuleOS

os.error

The functions in this module defines the OS level errors. It raises OSError in case of invalid or inaccessible file names and path etc.

Example

Output:

Problem reading: Python.txt

os.popen()

This function opens a file to, or from the command specified and it returns a file object which is connected to a pipe.

Example

Output:

This is awesome

os.close()

This function closes the associated file with descriptor fd.

Example

Output:

Traceback (most recent call last):
  File "main.py", line 3, in 
    file = open(fr, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'Python1.txt'

os.rename

In this function, a file or directory can be renamed by using the function os.rename(). A user can rename the file if it has privilege to change the file.

Example

Output:

Traceback (most recent call last):
  File "main.py", line 3, in 
    os.rename(fd,'Python1.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'python.txt' -> 'Python1.txt'

os.access()

This function uses real uid/gid to test if the invoking user has access to the path.

Example

Output:

Exist path: False
It access to read the file: False
It access to write the file: False
Check if path can be executed: False
Next TopicPython Tutorial




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA