Quick: tell me how to write a text file one directory above the current working directory. If you are drawing a blank, there’s a valid reason. While you are often taught how to change the working directory to a different directory on your computer, your strangely never taught how to programmatically move to a different folder on a computer that is not your own. All that is about to change with this tutorial. (Side note: programmatically is defined as doing something without interaction. If I could interact with a computer to do this task, I would just click the “Up a folder” button or browse to the folder above the one I was just in using the file browser. Since I cannot interact with a computer directly, but indirectly through code, I must do it programmatically. ;)).
While all code should be Python 2 and 3 compatible unless otherwise noted, any
Exceptions are from Python 3.3+.
While I was trying to implement a blacklist in PatchIt! Version 1.1.1, I came up with a formula to copy the contents of the folder to be compressed one directory above the selected folder, sort through them, compress, then move everything back. But I ran into an issue from the get-go (and I’m sure you can guess what it is. :P). After a bit of research, I finally found a remedy, and it is surprising easy, and probably should be included in Python tutorials. It’s called
“Return the directory name of pathname
path. This is the first element of the pair returned by passing
pathto the function
As we can clearly read, this function gets the directory a file is located in, but says nothing about getting the directory above a directory! Don’t worry, we’re just about to into the code. 😉
Recalling that we get the current working directory by using
os.getcwd(), and we change the current working directory using
os.chdir(), we can combine these two plus our new found function to perform the action I posed at the beginning.
As you can see,
os.path.dirname() works on folder paths, and allowed me to programmatically write a file and read it back on your computer, without having to know the folder structure. This method allows you to move up any number of directories above the original current working directory by repeatedly running it, though I advice doing no more than twice, as even once could break your code if the working directory is the root of a HDD.
You have finished the course. You know how to move one folder above the current working directory. Now, get out there and put your new code to good use! 😀