Skip to content

OS Methods

This tutorial will teach you how to use the OS module to handle files and directories. OS methods are used to create, delete, rename, and move files and directories.

S.NoMethodDescriptionExample
1os.getcwd()Returns the current working directory.os.getcwd()
2os.chdir(path)Changes the current working directory to the specified path.os.chdir('C:\\Users\\User\\Desktop')
3os.listdir(path)Returns a list of all files and directories in the specified path.os.listdir('C:\\Users\\User\\Desktop')
4os.mkdir(path)Creates a directory in the specified path.os.mkdir('C:\\Users\\User\\Desktop\\New Folder')
5os.makedirs(path)Creates a directory in the specified path. If the parent directories do not exist, they will be created.os.makedirs('C:\\Users\\User\\Desktop\\New Folder\\New Folder')
6os.remove(path)Deletes the file at the specified path.os.remove('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
7os.rmdir(path)Deletes the directory at the specified path.os.rmdir('C:\\Users\\User\\Desktop\\New Folder\\New Folder')
8os.removedirs(path)Deletes the directory at the specified path. If the parent directories are empty, they will be deleted.os.removedirs('C:\\Users\\User\\Desktop\\New Folder\\New Folder')
9os.rename(src, dst)Renames the file or directory at the specified source path to the specified destination path.os.rename('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')
10os.replace(src, dst)Renames the file or directory at the specified source path to the specified destination path. If the destination path already exists, it will be replaced.os.replace('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')
11os.walk(path)Returns a generator that yields a tuple of three values for each directory in the specified path. The first value is the path of the directory, the second value is a list of the names of the subdirectories in the directory, and the third value is a list of the names of the files in the directory.os.walk('C:\\Users\\User\\Desktop\\New Folder')
12os.path.exists(path)Returns True if the file or directory at the specified path exists, otherwise returns False.os.path.exists('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
13os.path.isfile(path)Returns True if the file at the specified path exists, otherwise returns False.os.path.isfile('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
14os.path.isdir(path)Returns True if the directory at the specified path exists, otherwise returns False.os.path.isdir('C:\\Users\\User\\Desktop\\New Folder\\New Folder')
15os.path.getsize(path)Returns the size of the file at the specified path in bytes.os.path.getsize('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
16os.path.getmtime(path)Returns the time of the last modification of the file at the specified path.os.path.getmtime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
17os.path.getctime(path)Returns the time of the creation of the file at the specified path.os.path.getctime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
18os.path.getatime(path)Returns the time of the last access of the file at the specified path.os.path.getatime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
19os.path.abspath(path)Returns the absolute path of the file or directory at the specified path.os.path.abspath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
20os.path.dirname(path)Returns the directory name of the file or directory at the specified path.os.path.dirname('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
21os.path.basename(path)Returns the base name of the file or directory at the specified path.os.path.basename('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
22os.path.split(path)Returns a tuple of two values. The first value is the directory name of the file or directory at the specified path, and the second value is the base name of the file or directory at the specified path.os.path.split('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
23os.path.join(path1, path2)Joins the specified paths.os.path.join('C:\\Users\\User\\Desktop\\New Folder', 'New Folder')
24os.path.splitext(path)Splits the specified path into a tuple of two values. The first value is the path without the extension, and the second value is the extension.os.path.splitext('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
25os.path.normpath(path)Normalizes the specified path.os.path.normpath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
26os.path.relpath(path)Returns the relative path from the current working directory to the specified path.os.path.relpath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
27os.path.commonpath(paths)Returns the common path of the specified paths.os.path.commonpath(['C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'])
28os.path.commonprefix(paths)Returns the common prefix of the specified paths.os.path.commonprefix(['C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'])
29os.path.expanduser(path)Expands the specified path to the user’s home directory.os.path.expanduser('~\\Desktop\\New Folder\\New Folder\\file.txt')
30os.path.expandvars(path)Expands the specified path to the environment variables.os.path.expandvars('%USERPROFILE%\\Desktop\\New Folder\\New Folder\\file.txt')
31os.path.samefile(path1, path2)Returns True if the specified paths refer to the same file, otherwise returns False.os.path.samefile('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')
32os.path.sameopenfile(fp1, fp2)Returns True if the specified file objects refer to the same file, otherwise returns False.os.path.sameopenfile(open('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'), open('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))
33os.path.samestat(stat1, stat2)Returns True if the specified stat objects refer to the same file, otherwise returns False.os.path.samestat(os.stat('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'), os.stat('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))
34os.path.isabs(path)Returns True if the specified path is an absolute path, otherwise returns False.os.path.isabs('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')
35os.path.ismount(path)Returns True if the specified path is a mount point, otherwise returns False.os.path.ismount('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')

The os.getcwd() method returns the current working directory.

os_getcwd.py
import os
 
print(os.getcwd())

Output:

command
C:\Users\username>python os_getcwd.py
C:\Users\username

In the above example, we import the os module and use the os.getcwd() method to get the current working directory.

The os.chdir() method changes the current working directory to the specified path.

os_chdir.py
import os
 
os.chdir('C:\\Users\\User\\Desktop')
print(os.getcwd())

Output:

command
C:\Users\username>python os_chdir.py
C:\Users\username\Desktop

In the above example, we import the os module and use the os.chdir() method to change the current working directory to the Desktop directory.

The os.listdir() method returns a list of all files and directories in the specified path.

os_listdir.py
import os
 
print(os.listdir('C:\\Users\\User\\Desktop'))

Output:

command
C:\Users\username>python os_listdir.py
['New Folder', 'file.txt']

In the above example, we import the os module and use the os.listdir() method to get a list of all files and directories in the Desktop directory.

The os.mkdir() method creates a directory in the specified path.

os_mkdir.py
import os
 
os.mkdir('C:\\Users\\User\\Desktop\\New Folder')

Output:

command
C:\Users\username>python os_mkdir.py

In the above example, we import the os module and use the os.mkdir() method to create a directory named “New Folder” in the Desktop directory.

The os.makedirs() method creates a directory in the specified path. If the parent directories do not exist, they will be created.

os_makedirs.py
import os
 
os.makedirs('C:\\Users\\User\\Desktop\\New Folder\\New Folder')

Output:

command
C:\Users\username>python os_makedirs.py

In the above example, we import the os module and use the os.makedirs() method to create a directory named “New Folder” in the Desktop directory. Since the parent directory “New Folder” does not exist, it will be created.

The os.remove() method deletes the file at the specified path.

os_remove.py
import os
 
os.remove('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')

Output:

command
C:\Users\username>python os_remove.py

In the above example, we import the os module and use the os.remove() method to delete the file named “file.txt” in the “New Folder” directory.

The os.rmdir() method deletes the directory at the specified path.

os_rmdir.py
import os
 
os.rmdir('C:\\Users\\User\\Desktop\\New Folder\\New Folder')

Output:

command
C:\Users\username>python os_rmdir.py

In the above example, we import the os module and use the os.rmdir() method to delete the directory named “New Folder” in the Desktop directory.

The os.removedirs() method deletes the directory at the specified path. If the parent directories are empty, they will be deleted.

os_removedirs.py
import os
 
os.removedirs('C:\\Users\\User\\Desktop\\New Folder\\New Folder')

Output:

command
C:\Users\username>python os_removedirs.py

In the above example, we import the os module and use the os.removedirs() method to delete the directory named “New Folder” in the Desktop directory. Since the parent directory “New Folder” is empty, it will be deleted.

The os.rename() method renames the file or directory at the specified source path to the specified destination path.

os_rename.py
import os
 
os.rename('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')

Output:

command
C:\Users\username>python os_rename.py

In the above example, we import the os module and use the os.rename() method to rename the file named “file.txt” to “new_file.txt” in the “New Folder” directory.

The os.replace() method renames the file or directory at the specified source path to the specified destination path. If the destination path already exists, it will be replaced.

os_replace.py
import os
 
os.replace('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')

Output:

command
C:\Users\username>python os_replace.py

In the above example, we import the os module and use the os.replace() method to rename the file named “file.txt” to “new_file.txt” in the “New Folder” directory. Since the file “new_file.txt” already exists, it will be replaced.

The os.walk() method returns a generator that yields a tuple of three values for each directory in the specified path. The first value is the path of the directory, the second value is a list of the names of the subdirectories in the directory, and the third value is a list of the names of the files in the directory.

os_walk.py
import os
 
for root, dirs, files in os.walk('C:\\Users\\User\\Desktop\\New Folder'):
    print(root)
    print(dirs)
    print(files)

Output:

command
C:\Users\username>python os_walk.py
C:\Users\username\Desktop\New Folder
['New Folder']
['file.txt']
C:\Users\username\Desktop\New Folder\New Folder
[]
['new_file.txt']

In the above example, we import the os module and use the os.walk() method to get a generator that yields a tuple of three values for each directory in the “New Folder” directory. The first value is the path of the directory, the second value is a list of the names of the subdirectories in the directory, and the third value is a list of the names of the files in the directory.

The os.path.exists() method returns True if the file or directory at the specified path exists, otherwise returns False.

os_path_exists.py
import os
 
print(os.path.exists('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.exists('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_exists.py
True
False

In the above example, we import the os module and use the os.path.exists() method to check if the files “file.txt” and “new_file.txt” exist in the “New Folder” directory.

The os.path.isfile() method returns True if the file at the specified path exists, otherwise returns False.

os_path_isfile.py
import os
 
print(os.path.isfile('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.isfile('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_isfile.py
True
False

In the above example, we import the os module and use the os.path.isfile() method to check if the files “file.txt” and “new_file.txt” exist in the “New Folder” directory.

The os.path.isdir() method returns True if the directory at the specified path exists, otherwise returns False.

os_path_isdir.py
import os
 
print(os.path.isdir('C:\\Users\\User\\Desktop\\New Folder\\New Folder'))
print(os.path.isdir('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\New Folder'))

Output:

command
C:\Users\username>python os_path_isdir.py
True
False

In the above example, we import the os module and use the os.path.isdir() method to check if the directories “New Folder” and “New Folder” exist in the “New Folder” directory.

The os.path.getsize() method returns the size of the file at the specified path in bytes.

os_path_getsize.py
import os
 
print(os.path.getsize('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.getsize('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_getsize.py
11
0

In the above example, we import the os module and use the os.path.getsize() method to get the size of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.getmtime() method returns the time of the last modification of the file at the specified path.

os_path_getmtime.py
import os
 
print(os.path.getmtime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.getmtime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_getmtime.py
1634178000.0
1634178000.0

In the above example, we import the os module and use the os.path.getmtime() method to get the time of the last modification of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.getctime() method returns the time of the creation of the file at the specified path.

os_path_getctime.py
import os
 
print(os.path.getctime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.getctime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_getctime.py
1634178000.0
1634178000.0

In the above example, we import the os module and use the os.path.getctime() method to get the time of the creation of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.getatime() method returns the time of the last access of the file at the specified path.

os_path_getatime.py
import os
 
print(os.path.getatime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.getatime('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_getatime.py
1634178000.0
1634178000.0

In the above example, we import the os module and use the os.path.getatime() method to get the time of the last access of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.abspath() method returns the absolute path of the file or directory at the specified path.

os_path_abspath.py
import os
 
print(os.path.abspath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.abspath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_abspath.py
C:\Users\username\Desktop\New Folder\New Folder\file.txt
C:\Users\username\Desktop\New Folder\New Folder\new_file.txt

In the above example, we import the os module and use the os.path.abspath() method to get the absolute path of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.dirname() method returns the directory name of the file or directory at the specified path.

os_path_dirname.py
import os
 
print(os.path.dirname('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.dirname('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_dirname.py
C:\Users\username\Desktop\New Folder\New Folder
C:\Users\username\Desktop\New Folder\New Folder

In the above example, we import the os module and use the os.path.dirname() method to get the directory name of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.basename() method returns the base name of the file or directory at the specified path.

os_path_basename.py
import os
 
print(os.path.basename('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.basename('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_basename.py
file.txt
new_file.txt

In the above example, we import the os module and use the os.path.basename() method to get the base name of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.split() method returns a tuple of two values. The first value is the directory name of the file or directory at the specified path, and the second value is the base name of the file or directory at the specified path.

os_path_split.py
import os
 
print(os.path.split('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.split('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_split.py
('C:\\Users\\username\\Desktop\\New Folder\\New Folder', 'file.txt')
('C:\\Users\\username\\Desktop\\New Folder\\New Folder', 'new_file.txt')

In the above example, we import the os module and use the os.path.split() method to get a tuple of two values. The first value is the directory name of the files “file.txt” and “new_file.txt” in the “New Folder” directory, and the second value is the base name of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.join() method joins the specified paths.

os_path_join.py
import os
 
print(os.path.join('C:\\Users\\User\\Desktop\\New Folder', 'New Folder'))
print(os.path.join('C:\\Users\\User\\Desktop\\New Folder', 'New Folder', 'file.txt'))
print(os.path.join('C:\\Users\\User\\Desktop\\New Folder', 'New Folder', 'new_file.txt'))

Output:

command
C:\Users\username>python os_path_join.py
C:\Users\username\Desktop\New Folder\New Folder
C:\Users\username\Desktop\New Folder\New Folder\file.txt
C:\Users\username\Desktop\New Folder\New Folder\new_file.txt

In the above example, we import the os module and use the os.path.join() method to join the specified paths.

The os.path.splitext() method splits the specified path into a tuple of two values. The first value is the path without the extension, and the second value is the extension.

os_path_splitext.py
import os
 
print(os.path.splitext('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.splitext('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_splitext.py
('C:\\Users\\username\\Desktop\\New Folder\\New Folder\\file', '.txt')
('C:\\Users\\username\\Desktop\\New Folder\\New Folder\\new_file', '.txt')

In the above example, we import the os module and use the os.path.splitext() method to get a tuple of two values. The first value is the path without the extension of the files “file.txt” and “new_file.txt” in the “New Folder” directory, and the second value is the extension of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.normpath() method normalizes the specified path.

os_path_normpath.py
import os
 
print(os.path.normpath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.normpath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_normpath.py
C:\Users\username\Desktop\New Folder\New Folder\file.txt
C:\Users\username\Desktop\New Folder\New Folder\new_file.txt

In the above example, we import the os module and use the os.path.normpath() method to normalize the paths of the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.relpath() method returns the relative path from the current working directory to the specified path.

os_path_relpath.py
import os
 
print(os.path.relpath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.relpath('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_relpath.py
..\
..\new_file.txt

In the above example, we import the os module and use the os.path.relpath() method to get the relative path from the current working directory to the files “file.txt” and “new_file.txt” in the “New Folder” directory.

The os.path.commonpath() method returns the common path of the specified paths.

os_path_commonpath.py
import os
 
print(os.path.commonpath(['C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt']))
print(os.path.commonpath(['C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt']))

Output:

command
C:\Users\username>python os_path_commonpath.py
C:\Users\username\Desktop\New Folder\New Folder
C:\Users\username\Desktop\New Folder\New Folder

In the above example, we import the os module and use the os.path.commonpath() method to get the common path of the specified paths.

The os.path.commonprefix() method returns the common prefix of the specified paths.

os_path_commonprefix.py
import os
 
print(os.path.commonprefix(['C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt']))
print(os.path.commonprefix(['C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt']))

Output:

command
C:\Users\username>python os_path_commonprefix.py
C:\Users\username\Desktop\New Folder\New Folder\
C:\Users\username\Desktop\New Folder\New Folder\

In the above example, we import the os module and use the os.path.commonprefix() method to get the common prefix of the specified paths.

The os.path.expanduser() method expands the specified path to the user’s home directory.

os_path_expanduser.py
import os
 
print(os.path.expanduser('~\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.expanduser('~\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_expanduser.py
C:\Users\username\Desktop\New Folder\New Folder\file.txt
C:\Users\username\Desktop\New Folder\New Folder\new_file.txt

In the above example, we import the os module and use the os.path.expanduser() method to expand the paths of the files “file.txt” and “new_file.txt” in the “New Folder” directory to the user’s home directory.

The os.path.expandvars() method expands the specified path to the environment variables.

os_path_expandvars.py
import os
 
print(os.path.expandvars('%USERPROFILE%\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.expandvars('%USERPROFILE%\\Desktop\\New Folder\\New Folder\\new_file.txt'))

Output:

command
C:\Users\username>python os_path_expandvars.py
C:\Users\username\Desktop\New Folder\New Folder\file.txt
C:\Users\username\Desktop\New Folder\New Folder\new_file.txt

In the above example, we import the os module and use the os.path.expandvars() method to expand the paths of the files “file.txt” and “new_file.txt” in the “New Folder” directory to the environment variables.

The os.path.samefile() method returns True if the specified paths refer to the same file, otherwise returns False.

os_path_samefile.py
import os
 
print(os.path.samefile('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt'))
print(os.path.samefile('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt', 'C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))

Output:

command
C:\Users\username>python os_path_samefile.py
False
True

In the above example, we import the os module and use the os.path.samefile() method to check if the paths of the files “file.txt” and “new_file.txt” in the “New Folder” directory refer to the same file.

The os.path.sameopenfile() method returns True if the specified file objects refer to the same file, otherwise returns False.

os_path_sameopenfile.py
import os
 
print(os.path.sameopenfile(open('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'), open('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')))
print(os.path.sameopenfile(open('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'), open('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')))

Output:

command
C:\Users\username>python os_path_sameopenfile.py
False
True

In the above example, we import the os module and use the os.path.sameopenfile() method to check if the file objects of the files “file.txt” and “new_file.txt” in the “New Folder” directory refer to the same file.

The os.path.samestat() method returns True if the specified stat objects refer to the same file, otherwise returns False.

os_path_samestat.py
import os
 
print(os.path.samestat(os.stat('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'), os.stat('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\new_file.txt')))
print(os.path.samestat(os.stat('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'), os.stat('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt')))

Output:

command
C:\Users\username>python os_path_samestat.py
False
True

In the above example, we import the os module and use the os.path.samestat() method to check if the stat objects of the files “file.txt” and “new_file.txt” in the “New Folder” directory refer to the same file.

The os.path.isabs() method returns True if the specified path is an absolute path, otherwise returns False.

os_path_isabs.py
import os
 
print(os.path.isabs('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.isabs('New Folder\\New Folder\\file.txt'))

Output:

command
C:\Users\username>python os_path_isabs.py
True
False

In the above example, we import the os module and use the os.path.isabs() method to check if the paths of the files “file.txt” and “new_file.txt” in the “New Folder” directory are absolute paths.

The os.path.ismount() method returns True if the specified path is a mount point, otherwise returns False.

os_path_ismount.py
import os
 
print(os.path.ismount('C:\\Users\\User\\Desktop\\New Folder\\New Folder\\file.txt'))
print(os.path.ismount('C:\\Users\\User\\Desktop\\New Folder\\New Folder'))
print(os.path.ismount('C:\\Users\\User\\Desktop\\New Folder'))
print(os.path.ismount('C:\\Users\\User\\Desktop'))
print(os.path.ismount('C:\\Users\\User'))
print(os.path.ismount('C:\\Users'))
print(os.path.ismount('C:\\'))
print(os.path.ismount('C:'))

Output:

command
C:\Users\username>python os_path_ismount.py
False
False
False
False
False
False
True
False

In the above example, we import the os module and use the os.path.ismount() method to check if the paths of the files “file.txt” and “new_file.txt” in the “New Folder” directory are mount points.

The os.path module provides the following constants.

S.No.ConstantDescriptionExample
1os.path.sepReturns the path separator.os.path.sep
2os.path.altsepReturns the alternate path separator.os.path.altsep
3os.path.extsepReturns the extension separator.os.path.extsep
4os.path.pathsepReturns the path separator used in PATH environment variables.os.path.pathsep
5os.path.defpathReturns the default search path for executables.os.path.defpath
6os.path.devnullReturns the null device.os.path.devnull
7os.path.supports_unicode_filenamesReturns True if the operating system supports Unicode filenames, otherwise returns False.os.path.supports_unicode_filenames
8os.path.curdirReturns the current directory.os.path.curdir
9os.path.pardirReturns the parent directory.os.path.pardir

The os.path.sep constant returns the path separator.

os_path_sep.py
import os
 
print(os.path.sep)

Output:

command
C:\Users\username>python os_path_sep.py
\

In the above example, we import the os module and use the os.path.sep constant to get the path separator.

The os.path.altsep constant returns the alternate path separator.

os_path_altsep.py
import os
 
print(os.path.altsep)

Output:

command
C:\Users\username>python os_path_altsep.py
/

In the above example, we import the os module and use the os.path.altsep constant to get the alternate path separator.

The os.path.extsep constant returns the extension separator.

os_path_extsep.py
import os
 
print(os.path.extsep)

Output:

command
C:\Users\username>python os_path_extsep.py
.

In the above example, we import the os module and use the os.path.extsep constant to get the extension separator.

The os.path.pathsep constant returns the path separator used in PATH environment variables.

os_path_pathsep.py
import os
 
print(os.path.pathsep)

Output:

command
C:\Users\username>python os_path_pathsep.py
;

In the above example, we import the os module and use the os.path.pathsep constant to get the path separator used in PATH environment variables.

The os.path.defpath constant returns the default search path for executables.

os_path_defpath.py
import os
 
print(os.path.defpath)

Output:

command
C:\Users\username>python os_path_defpath.py
.;C:\bin

In the above example, we import the os module and use the os.path.defpath constant to get the default search path for executables.

The os.path.devnull constant returns the null device.

os_path_devnull.py
import os
 
print(os.path.devnull)

Output:

command
C:\Users\username>python os_path_devnull.py
nul

In the above example, we import the os module and use the os.path.devnull constant to get the null device.

os.path.supports_unicode_filenames Constant

Section titled “os.path.supports_unicode_filenames Constant”

The os.path.supports_unicode_filenames constant returns True if the operating system supports Unicode filenames, otherwise returns False.

os_path_supports_unicode_filenames.py
import os
 
print(os.path.supports_unicode_filenames)

Output:

command
C:\Users\username>python os_path_supports_unicode_filenames.py
True

In the above example, we import the os module and use the os.path.supports_unicode_filenames constant to check if the operating system supports Unicode filenames.

The os.path.curdir constant returns the current directory.

os_path_curdir.py
import os
 
print(os.path.curdir)

Output:

command
C:\Users\username>python os_path_curdir.py
.

In the above example, we import the os module and use the os.path.curdir constant to get the current directory.

The os.path.pardir constant returns the parent directory.

os_path_pardir.py
import os
 
print(os.path.pardir)

Output:

command
C:\Users\username>python os_path_pardir.py
..

In the above example, we import the os module and use the os.path.pardir constant to get the parent directory.

The os module provides the following constants.

S.No.ConstantDescriptionExample
1os.nameReturns the name of the operating system.os.name
2os.curdirReturns the current directory.os.curdir
3os.pardirReturns the parent directory.os.pardir
4os.sepReturns the path separator.os.sep
5os.extsepReturns the extension separator.os.extsep
6os.altsepReturns the alternate path separator.os.altsep
7os.pathsepReturns the path separator used in PATH environment variables.os.pathsep
8os.linesepReturns the line separator.os.linesep
9os.defpathReturns the default search path for executables.os.defpath
10os.devnullReturns the null device.os.devnull
11os.environReturns a dictionary of the environment variables.os.environ
12os.supports_bytes_environReturns True if the operating system supports environment variables as bytes, otherwise returns False.os.supports_bytes_environ
13os.supports_dir_fdReturns True if the operating system supports the dir_fd parameter, otherwise returns False.os.supports_dir_fd
14os.supports_effective_idsReturns True if the operating system supports the effective_ids parameter, otherwise returns False.os.supports_effective_ids
15os.supports_fdReturns True if the operating system supports the fd parameter, otherwise returns False.os.supports_fd
16os.supports_follow_symlinksReturns True if the operating system supports the follow_symlinks parameter, otherwise returns False.os.supports_follow_symlinks

The os.name constant returns the name of the operating system.

os_name.py
import os
 
print(os.name)

Output:

command
C:\Users\username>python os_name.py
nt

In the above example, we import the os module and use the os.name constant to get the name of the operating system.

The os.curdir constant returns the current directory.

os_curdir.py
import os
 
print(os.curdir)

Output:

command
C:\Users\username>python os_curdir.py
.

In the above example, we import the os module and use the os.curdir constant to get the current directory.

The os.pardir constant returns the parent directory.

os_pardir.py
import os
 
print(os.pardir)

Output:

command
C:\Users\username>python os_pardir.py
..

In the above example, we import the os module and use the os.pardir constant to get the parent directory.

The os.sep constant returns the path separator.

os_sep.py
import os
 
print(os.sep)

Output:

command
C:\Users\username>python os_sep.py
\

In the above example, we import the os module and use the os.sep constant to get the path separator.

The os.extsep constant returns the extension separator.

os_extsep.py
import os
 
print(os.extsep)

Output:

command
C:\Users\username>python os_extsep.py
.

In the above example, we import the os module and use the os.extsep constant to get the extension separator.

The os.altsep constant returns the alternate path separator.

os_altsep.py
import os
 
print(os.altsep)

Output:

command
C:\Users\username>python os_altsep.py
/

In the above example, we import the os module and use the os.altsep constant to get the alternate path separator.

The os.pathsep constant returns the path separator used in PATH environment variables.

os_pathsep.py
import os
 
print(os.pathsep)

Output:

command
C:\Users\username>python os_pathsep.py
;

In the above example, we import the os module and use the os.pathsep constant to get the path separator used in PATH environment variables.

The os.linesep constant returns the line separator.

os_linesep.py
import os
 
print(os.linesep)

Output:

command
C:\Users\username>python os_linesep.py
 
 

In the above example, we import the os module and use the os.linesep constant to get the line separator.

The os.defpath constant returns the default search path for executables.

os_defpath.py
import os
 
print(os.defpath)

Output:

command
C:\Users\username>python os_defpath.py
.;C:\bin

In the above example, we import the os module and use the os.defpath constant to get the default search path for executables.

The os.devnull constant returns the null device.

os_devnull.py
import os
 
print(os.devnull)

Output:

command
C:\Users\username>python os_devnull.py
nul

In the above example, we import the os module and use the os.devnull constant to get the null device.

The os.environ constant returns a dictionary of the environment variables.

os_environ.py
import os
 
print(os.environ)

Output:

command
C:\Users\username>python os_environ.py
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\ravi\\AppData\\Roaming', 'CHOCOLATEYINSTALL': 'C:\\ProgramData\\chocolatey', 'CLASS_PATH': 'C:\\mysql-connector-j-8.0.33.jar', 'CLINK_DIR': 'C:\\Program Files (x86)\\clink', 'CLINK_DUMMY_CAPTURE_ENV': ' ', 'COLUMNS': '110', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'RAVI', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'EFC_24904': '1', 'GOPATH': 'C:\\Users\\ravi\\go', 'HOME': 'C:\\Users\\ravi', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\ravi', 'INTELLIJ IDEA COMMUNITY EDITION': 'C:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition 2023.2.2\\bin;', 'LINES': '25', 'LOCALAPPDATA': 'C:\\Users\\ravi\\AppData\\Local', 'LOGONSERVER': '\\\\RAVI', 'NUMBER_OF_PROCESSORS': '8', 'ONEDRIVE': 'C:\\Users\\ravi\\OneDrive', 'ONEDRIVECONSUMER': 'C:\\Users\\ravi\\OneDrive'})

In the above example, we import the os module and use the os.environ constant to get a dictionary of the environment variables.

The os.supports_bytes_environ constant returns True if the operating system supports environment variables as bytes, otherwise returns False.

os_supports_bytes_environ.py
import os
 
print(os.supports_bytes_environ)

Output:

command
C:\Users\username>python os_supports_bytes_environ.py
True

In the above example, we import the os module and use the os.supports_bytes_environ constant to check if the operating system supports environment variables as bytes.

The os.supports_dir_fd constant returns True if the operating system supports the dir_fd parameter, otherwise returns False.

os_supports_dir_fd.py
import os
 
print(os.supports_dir_fd)

Output:

command
C:\Users\username>python os_supports_dir_fd.py
True

In the above example, we import the os module and use the os.supports_dir_fd constant to check if the operating system supports the dir_fd parameter.

The os.supports_effective_ids constant returns True if the operating system supports the effective_ids parameter, otherwise returns False.

os_supports_effective_ids.py
import os
 
print(os.supports_effective_ids)

Output:

command
C:\Users\username>python os_supports_effective_ids.py
True

In the above example, we import the os module and use the os.supports_effective_ids constant to check if the operating system supports the effective_ids parameter.

The os.supports_fd constant returns True if the operating system supports the fd parameter, otherwise returns False.

os_supports_fd.py
import os
 
print(os.supports_fd)

Output:

command
C:\Users\username>python os_supports_fd.py
True

In the above example, we import the os module and use the os.supports_fd constant to check if the operating system supports the fd parameter.

The os.supports_follow_symlinks constant returns True if the operating system supports the follow_symlinks parameter, otherwise returns False.

os_supports_follow_symlinks.py
import os
 
print(os.supports_follow_symlinks)

Output:

command
C:\Users\username>python os_supports_follow_symlinks.py
True

In the above example, we import the os module and use the os.supports_follow_symlinks constant to check if the operating system supports the follow_symlinks parameter.

In this tutorial, we have learned about the os module in Python. We have also learned about the os.path module and its methods and constants with examples. Finally, we have learned about the os module and its constants with examples. Now you can use the os module and its methods and constants in your Python program to perform various operating system-related tasks. For more information, visit the official documentation of the os module. For more tutorials, visit Python Central Hub.


diagram a path check answers about a moment that has already passed mermaid
exists, isfile and isdir each ask the filesystem a question and return an answer that was true when it was asked. Between that answer and whatever you do next, anything can change -- so a check followed by an action is two operations, not one, and the gap between them is where the bug lives.
sketch Three path questions, and why checking first does not help p5.js
exists, isfile and isdir disagree on purpose, and the top panel shows what each returns for a file, a directory and a missing path. The lower half is the timing problem: the check and the action are separate operations, so the answer can be stale by the time you act on it. Attempting the operation and handling the failure has no gap.
pch.quizTag pch.quizDefaultTitle
  1. `os.path.exists(p)` returns True. Is `p` a file?

    pch.quizShowAnswer

    B — Not necessarily — it is True for a directory too — Verified: a directory reports `exists=True, isfile=False, isdir=True`. Use `isfile` when you mean a file.

  2. Why is `if os.path.exists(p): open(p)` not actually safe?

    pch.quizShowAnswer

    B — They are two separate operations, and the file can vanish in between — A time-of-check to time-of-use race. The check answers about a moment that has already passed by the time you act on it.

  3. What is the more robust pattern?

    pch.quizShowAnswer

    B — Attempt the operation inside `try`/`except` — one operation, no gap — This is the same EAFP reasoning as `dict` access: attempting is atomic where check-then-act is not. The check is still fine for a friendly message, never as a guarantee.

  4. What does `os.path.isfile` return for a path that does not exist?

    pch.quizShowAnswer

    A — `False` — All three predicates return False for a missing path rather than raising, which is why they compose into readable conditions — and why none of them distinguishes 'missing' from 'wrong kind'.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading