This content originally appeared on DEV Community and was authored by Aya Bouchiha
Hello,
I'm Aya Bouchiha,
today,
I'm going to share with you 6 useful os module methods.
Firstly, we need to know that the os module is built-in in python, it is used for interacting with the operating system.
getcwd()
getcwd(): this method helps you to get the absolute path of the current working directory as a string.
import os
print(os.getcwd())
# C:\Users\AyaBouchiha\Desktop\posts
os.mkdir()
mkdir(): lets you create a new directory if it does not exists, else it raises an error (FileExistsError)
import os
os.mkdir('python') # done :)
os.mkdir('python') # error (FileExistsError)
os.rmdir()
rmdir(): helps you to remove an empty directory.
import os
# done
os.mkdir('python/newFolder')
# done
os.rmdir('python/newFolder')
# error (FileNotFoundError)
os.rmdir('something/does-not-exists')
# error (NotADirectoryError)
os.rmdir('user.json')
os.remove()
remove(): lets you delete a file. If it does not exists, this method raises an error.
import os
# done
os.remove('posts/python/test.py')
# error(FileNotFoundError)
os.remove('posts/python/test.py')
os.path.isfile()
isfile(): returns True if the given path is a regular file, otherwise It returns False.
import os
my_file_path = 'posts/python/os_module.py'
# True
print(os.path.isfile(my_file_path))
file_does_not_exists_path = 'posts/python/os_module.json'
# False
print(os.path.isfile(file_does_not_exists_path))
directory_path = 'posts/python'
# False
print(os.path.isfile(directory_path))
os.listdir()
listdir(): returns a list that contains all files and directories names that exist in the specified path.
import os
print(os.listdir('posts/'))
# Output:
# [
# '5_list_python_methods.md',
# 'js_resources.md',
# 'MapObject.md',
# 'os_module.md',
# 'os_module.py',
# 'python'
# ]
Summary
getcwd(): returns the absolute path of the current working directory as a string.
mkdir(): creates a new directory.
rmdir(): removes an empty directory.
remove(): deletes a file.
isfile(): returns True if the given path is a regular file.
listdir(): returns a list that contains all files and directories names that exist in the specified path.
Suggested posts
To Contact Me:
- email: developer.aya.b@gmail.com
- telegram: AyaBouchiha
Have a great day!
This content originally appeared on DEV Community and was authored by Aya Bouchiha
Aya Bouchiha | Sciencx (2021-08-02T23:19:13+00:00) 6 Helpful OS Module Methods. Retrieved from https://www.scien.cx/2021/08/02/6-helpful-os-module-methods/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.