1import os
2
3Executing a shell command
4os.system()
5
6Get the users environment
7os.environ()
8
9#Returns the current working directory.
10os.getcwd()
11
12Return the real group id of the current process.
13os.getgid()
14
15Return the current process’s user id.
16os.getuid()
17
18Returns the real process ID of the current process.
19os.getpid()
20
21Set the current numeric umask and return the previous umask.
22os.umask(mask)
23
24Return information identifying the current operating system.
25os.uname()
26
27Change the root directory of the current process to path.
28os.chroot(path)
29
30Return a list of the entries in the directory given by path.
31os.listdir(path)
32
33Create a directory named path with numeric mode mode.
34os.mkdir(path)
35
36Recursive directory creation function.
37os.makedirs(path)
38
39Remove (delete) the file path.
40os.remove(path)
41
42Remove directories recursively.
43os.removedirs(path)
44
45Rename the file or directory src to dst.
46os.rename(src, dst)
47
48Remove (delete) the directory path.
49os.rmdir(path)
50
1#the os module provides an operating system interface from Python
2import os
3#prints the name of the operating system
4print(os.name)
5#prints the absolute path for the module
6print(os.getcwd())
1# Delete everything reachable from the directory named in "top",
2# assuming there are no symbolic links.
3# CAUTION: This is dangerous! For example, if top == '/', it
4# could delete all your disk files.
5import os
6for root, dirs, files in os.walk(top, topdown=False):
7 for name in files:
8 os.remove(os.path.join(root, name))
9 for name in dirs:
10 os.rmdir(os.path.join(root, name))
11
1The OS module in Python provides a way of using operating system dependent
2functionality.
3
4The functions that the OS module provides allows you to interface with the
5underlying operating system that Python is running on – be that Windows, Mac or
6Linux.
7
8You can find important information about your location or about the process.
9
10In this post I will show some of these functions.
1# Import the built-in os module
2import os
3# os.system() function
4os.system('echo Hello world!')
1>>> import os
2>>> os.getcwd() # Return the current working directory
3'C:\\Python39'
4>>> os.chdir('/server/accesslogs') # Change current working directory
5>>> os.system('mkdir today') # Run the command mkdir in the system shell
60
7