Python 3, OS, Example in Windows 10
If you are creating a program for a user where you want to store or use a file in the users home directory, it is not as easy as simply preparing a fixed file location like:
C:\Users\yagisanatode\
Because if another user on another computer tries to use your program they will start getting errors because their home directory might be something else like:
C:\Users\batman\
You can, however, get the users home directory by using Python’s os.path.expanduser
method.
1 2 3 4 5 |
>>> import os >>> home = os.path.expanduser('~') >>> home 'C:\\Users\\yagisanatode' >>> |
Great. Now we want to add the folder we want to store a file in or get a file from. Here we use the os.path.join
method. For example, let’s say we are creating a file downloader and we want the file to download to the user Downloads folder in Windows.
1 2 3 4 |
>>> location = os.path.join(home, 'Downloads') >>> location 'C:\\Users\\scott\\Downloads' >>> |
Got it! But…what if the user is a bit of a nonconformist and likes to rename their folders. It would probably be a good idea to check to ensure that this Downloads folder exists. To do this we can use the os.path.isdir
method.
1 2 3 4 |
>>> folder_check = os.path.isdir(location) >>> folder_check True >>> |
Example: The Home Folder Checker
Let’s look at a simple example of how to use these os.path
methods.
In the following example, we are creating a program that checks to see if folders exist in the user’s home directory. I’ll be running the program in Windows 10.
I’ll run through the program step-by-step in a moment. Just skip over what you already know.
Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
""" Python 3 Find main users directories like: 'Downloads' 'Desktop' 'Documents' 'Pictures' Then chech to see if they exist. """ import os def folder_name(): #Gets the home directory home = os.path.expanduser('~') folder_name_input = input("Type in the folder to see if it exists at: {}\\".format(home)) directory_check(home, folder_name_input) def directory_check(home, folder): #Joins the home directior to the users typed in folder folder_path = os.path.join(home,folder) #Checks to see if the folder exsists folder_check = os.path.isdir(folder_path) if folder_check is True: print(folder_path + " is a valid directory.") request_go_again() else: print(folder_path + " is NOT a valid directory") request_go_again() def request_go_again(): #Makes a request to go again. go_again = input("Do you want to check another folder? (y/n): ") print(go_again) if go_again[:1] is "y" or go_again[:1] is "Y": redo = folder_name() elif go_again[:1] is "n" or go_again[:1] is "N": print("Okay, bye.") else: print(" Please choose 'y' or 'n'") request_go_again() print("Check to see if the folder exists for this user's home directory.\n" "Just input a folder like 'Donwloads' and it will check it.\n ") #Starts the first check start_check = folder_name() |
Here’s is an example of the program running in the Python Shell. Remember, if you are running the program on your PC, the user will be your name or alias.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> RESTART: C:\Users\yagisantatode\Documents\Programming\Training\Python\OS\FindUsersDirectoryAndCheckExists.py Check to see if the folder exists for this user's home directory. Just input a folder like 'Donwloads' and it will check it. Type in the folder to see if it exists at: C:\Users\yagisantatode\Downloads C:\Users\yagisantatode\Downloads is a valid directory. Do you want to check another folder? (y/n): y y Type in the folder to see if it exists at: C:\Users\yagisantatode\Pictures C:\Users\yagisantatode\Pictures is a valid directory. Do you want to check another folder? (y/n): Y Y Type in the folder to see if it exists at: C:\Users\yagisantatode\Bananas C:\Users\yagisantatode\Bananas is NOT a valid directory Do you want to check another folder? (y/n): Sure Sure Please choose 'y' or 'n' Do you want to check another folder? (y/n): y y Type in the folder to see if it exists at: C:\Users\yagisantatode\Desktop C:\Users\yagisantatode\Desktop is a valid directory. Do you want to check another folder? (y/n): yes yes Type in the folder to see if it exists at: C:\Users\yagisantatode\Videos C:\Users\yagisantatode\Videos is a valid directory. Do you want to check another folder? (y/n): Yep Yep Type in the folder to see if it exists at: C:\Users\yagisantatode\Donkey C:\Users\yagisantatode\Donkey is NOT a valid directory Do you want to check another folder? (y/n): n n Okay, bye. >>> |
Pretty simple, right? Let’s see how it works:
Example Step-by-Step
12 13 14 |
import os |
First, in line 13 we import the os
library. We could have been a little more efficient here by just importing the path
module with:
from os import path
folder_name
16 17 18 19 20 |
def folder_name(): #Gets the home directory home = os.path.expanduser('~') folder_name_input = input("Type in the folder to see if it exists at: {}\\".format(home)) directory_check(home, folder_name_input) |
Here we create a function called folder_name
. On line 18, we create the variable home
to store the user’s file path.
On line 19 we create the variable folder_name_input
to store the input from the user. You’ll probably also notice the weird curly brackets “{}
” just before the two backslashes at the end of the instructions inside the input. From Python 3 this is the standard place-marker. At the end of the string you add .format(something)
, where the something could be a variable or a returned function that is a string. That something then appears between the brackets. In this case, we are calling the home variable that is a string of the user’s home file path. We then add two backslashes (one is escaped so we will need to add another for it to come up on the screen) so the user can see that they can the folder name to their file path.
Finally on line 20, we send the input and the home directory data to the directory_check
function.
directory_check
23 24 25 26 27 28 29 30 31 32 33 |
def directory_check(home, folder): #Joins the home directior to the users typed in folder folder_path = os.path.join(home,folder) #Checks to see if the folder exsists folder_check = os.path.isdir(folder_path) if folder_check is True: print(folder_path + " is a valid directory.") request_go_again() else: print(folder_path + " is NOT a valid directory") request_go_again() |
The directory_check
function takes the two variables we created from the folder_name
function, the home directory and the folder name that the user puts in to search.
On line 25, we join the home directory to the folder. Then on line 27, we check to see if the whole thing is a valid file path and store the Boolean True
or False
in the variable folder_check
.
On line 28, if the folder_check
proved that the file path we created exists, then we want to tell the user that is is a valid directory (line 29). Then, as a courtesy, we pass the request_go_again
function to see if the user wants to look up another directory.
On line 31, if the folder_check
proved that the file path we created did not exist. Here we inform the user that there is no such file in this home directory. Again, we ask if the useR wants to try another directory on line 33.
request_go_again
35 36 37 38 39 40 41 42 43 44 45 |
def request_go_again(): #Makes a request to go again. go_again = input("Do you want to check another folder? (y/n): ") print(go_again) if go_again[:1] is "y" or go_again[:1] is "Y": redo = folder_name() elif go_again[:1] is "n" or go_again[:1] is "N": print("Okay, bye.") else: print(" Please choose 'y' or 'n'") request_go_again() |
The request_go_again function is pretty self-explanatory, it asks the user if they wish to see if another folder exists in the home directory. The bulk of this function is then cleaning up user input to ensure they get to where they wanted.
Line 37, asks if the user wants to try another folder location and offers a yes or no (y/n) option.
We then print (Line 38) their response to make them feel bad when they can’t follow simple instructions. Joking…kinda.
In lines 39 and 40, the user chose the ‘y’so we call the folder_name
function so that they can start the process again. In the if
statement we check to see if they used capital letters or not and we just check the first letter of the input just in case they wrote out ‘yes’ in its entirety.
In lines 41-42, the user chose ‘n’, or some variant, so we simply printed out our farewell and left the user to the whim of the Python shell.
Finally, we have the catch-all for those with chaotic, anti-establishment personalities who chose not to type ‘y’ or ‘n’ or their variants.
Starting the Program
49 50 51 52 53 |
print("Check to see if the folder exists for this user's home directory.\n" "Just input a folder like 'Donwloads' and it will check it.\n ") #Starts the first check start_check = folder_name() |
At line 49, we start the program with some instructions. Then on line 53 we initialize the folder_name
function to start the whole process.
Conclusion
The os.path
operations, expanduser
, join
and isdir
, have numerous uses. They are ideal for checking directories and for helping your programs easily access the user’s home paths. One use of these operations that we will look at in the future is to combine them to set a download location for the use; so long as they have the folder ‘Downloads’ in their home directory.
Want to learn how to automate your daily admin at work with Python? Udemy has some great Python automation courses that will help you learn how to automate your tasks so you can focus on what really matters.
Got a more specific problem you need help with, but don’t have the time to develop the skills? Fiverr’s your best bet to find a skilled professional to solve your problem quickly and cheaply. *
*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.