Different separators in the os module in Python

The os module

The os module in Python provides functions that help to interact with the underlying operating system.

Different separator constants of the os module

The os module contains different separator constants that indicate different file separators used in different operating systems. The constants are as follows:

  1. os.sep
  2. os.altsep
  3. os.extsep
  4. os.pathsep
  5. os.linesep

os.sep

The os.sep indicates the character used by the operating system to separate pathname components. The value for os.sep is / for POSIX and \\ for Windows.

os.altsep

The os.altsep represents the operating system’s alternate character for separating pathname components, or None if only one separator character is available. On Windows systems when os.sep is a backslash, this is set to /.

os.extsep

The os.extsep indicates the character which separates the base filename from the extension.

os.pathsep

The os.pathsep indicates the character used by the operating system to separate search path components. The value for os.pathsep is : for POSIX and ; for Windows.

os.linesep

The os.linesep indicates the character used by the operating system to terminate lines. The value for os.linesep is \n for POSIX and \r\n for Windows.

Code

Let’s look at the code below:

import sys, os
print("Separators for %s operating system are as follows:" % (sys.platform))
print("os.sep = ", os.sep)
print("os.altsep = ", os.altsep)
print("os.extsep = " , os.extsep)
print("os.pathsep = ", os.pathsep)
print("os.linesep = ", os.linesep)

Code explanation

  • Line 1: We import the required modules.
  • Line 3: We obtain the current operating system using the sys.platform constant.
  • Line 4: We print the os.sep.
  • Line 5: We print the os.altsep.
  • Line 6 - We print the os.extsep .
  • Line 7: We print the os.pathsep.
  • Line 8: We print the os.linesep.

Free Resources