OS Module
The OS Module
To import:
import osGet 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:
Making multiple directories
This can be run once for the same reasons as making a folder
Remove directory
If the folder is not empty it will not delete it, same as Linux
os.rmdirdoes not work on files, same as rmdir in Linux
To remove in general, it is same as Linux
Can be run only once if the file does not exits
To prevent this, you can use the same
ifstatement check in order to see if it exists
Rename files
Traversing directories
By "walking":
The first variable prints the
path to the fileThe second variable prints the
foldersinside the path providedThe third variable prints the
filesinside 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
Join method
Usually used when the path to folder is questionable
Such as does it contain a
/at the end or not?
Return just the filename
Return just the directory
Return both directory path and filename separately
Check if path exists
Usually used as a if statement
Check if directory exits
Check if file exists
Exclude file format
Last updated