Python OS Module Guide
The OS module is a built-in module in Python that allows interaction with the operating system. Here are some common examples of using the OS module:
- Get the current working directory.
import os
current_dir = os.getcwd()
print(current_dir)
- Create a folder:
import os
os.mkdir("new_directory")
- Remove directory.
import os
os.rmdir("directory_to_delete")
- List the files and subdirectories in the directory.
import os
contents = os.listdir("directory_path")
for item in contents:
print(item)
- Check if the file or directory exists:
import os
exists = os.path.exists("file_or_directory_path")
if exists:
print("File or directory exists!")
else:
print("File or directory does not exist!")
- Execute operating system command:
import os
os.system("command_to_execute")
This is just a small example of the functions of the OS module, there are other functions such as file operations, path operations, environment variables, and more. You can refer to the official Python documentation or other tutorials for more ways to use it.