OS Module
The OS Module
To import:
import os
Get current working directory
# pwd in linux
os.getcwd()
Change directory
# cd in linux
os.chdir("/Path/To/Wanted/Directory")
List content of directory
# ls in linux
os.listdir()
Make a folder
# mkdir in linux
os.mkdir("Name_of_folder_you_want")
Can only be run once, as if the folder exists an error will be generated
[Errno 17] File exists: folder_name
Adding a conditional to check if the folder exits:
# os.listdir = lsdir in linux
if "myfolder" not in os.listdir("~/Desktop"):
os.mkdir("myfolder")
Making multiple directories
# mkdir -p /path/to/folder in linux
os.makedirs("/path/to/folder")
This can be run once for the same reasons as making a folder
Remove directory
# rmdir /path/to/directory in linux
os.rmdir("/path/to/directory")
If the folder is not empty it will not delete it, same as Linux
os.rmdir
does not work on files, same as rmdir in Linux
To remove in general, it is same as Linux
# rm /path/to/file in linux
os.remove("/path/to/file")
Can be run only once if the file does not exits
To prevent this, you can use the same
if
statement check in order to see if it exists
# rm -rf /path/to/directory in linux
os.removedirs("/path/to/directory")
Rename files
# mv current_name new_name in linux
os.rename("current_name", "new_name")
Traversing directories
# Unpacking
for directory_path, dirnames, filenames in os.walk("/location/to/folder"):
print(directory_path)
print(dirnames)
print(filenames)
By "walking":
The first variable prints the
path to the file
The second variable prints the
folders
inside the path providedThe third variable prints the
files
inside the path provided
After which, if it finds a folder it goes on level deeper within the directory structure
After which it starts the process again
If multiple folders, it will take them separately and "walk" through them until the end
Getting the environment variable
# Getting the HOME variable
# echo $HOME in linux
os.environ.get("HOME")
Join method
Usually used when the path to folder is questionable
Such as does it contain a
/
at the end or not?
# Concatinates basically ~/my_file.txt
os.path.join(os.environ.get("HOME"), "my_file.txt")
Return just the filename
# Will return just file.txt
print(os.path.basename("/path/to/file.txt"))
Return just the directory
# Will return just the "/path/to" folder structure, not the file
print(os.path.dirname("/path/to/file.txt"))
Return both directory path and filename separately
# Will return a tuple with directory and filename
print(os.path.split("/path/to/file.txt"))
# Example tuple: ("/path/to", "file.txt")
Check if path exists
# Boolean expression
os.path.exists("/path/to/file.txt")
# Returns True or Flase
Usually used as a if statement
Check if directory exits
os.path.isdir("/path/to/file.txt")
Check if file exists
os.path.isfile("/path/to/file.txt")
Exclude file format
# Prints the entire path + extension in tuple
os.path.splitext("/path/to/file.txt")
# Example: ("/path/to/file", ".txt")
Last updated