Despite being over three decades old, Python is still an extremely relevant and popular programming language. The fact that it’s easy to understand, and works on a variety of platforms with little to no modification of code, along with its community support and deep integration with various libraries, make it a “must-have” tool in the arsenal of any web developer. In this article, I’ll show you how to use Python to change the working directory. This is an entry-level command in Python and is a perfect exercise for someone who wants to get used to how Python assigns variables and see how basic error handling works.
According to the TIOBE Index, Python is the #1 programming language of choice compared to others on the list like JavaScript, C++, and C#. So it’s well worth your time to get familiar with it.
Check if you Have Python Installed
Before you can run Python commands, you should first check to see if it’s installed on your system. To do this, you can run one of the two following commands:
python --version
python3 --version
Generally, the “python” command refers to Python version 2, and “python3” refers to version 3. While the latter was released in 2008, python3’s usage really spiked in 2020 when the last major Python 2 version was discontinued in January 2020. Since then, it’s recommended to use “python3” whenever you can.
So if your system is new and you’re just getting started with Python, chances are that it’s version 3 and not version 2 that’s installed on your system. When I run the second command on my Linux server, here is what I see:
As you can see, I have Python version 3.10.12 installed. And if I want to run Python commands, I need to use “python3”, and not “python”.
Changing the Directory in Python
To just give the answer straight away, the command to change the directory in Python is the following:
os.chdir(new_directory)
Where “new_directory” is a variable containing the path to the location where you want to go. But this by itself doesn’t tell you how to actually use the command for changing your working directory, and in what context you would want to do so. To explain this, I have to first explain how commands are executed in Python, and then show you a sample script where we change the directory to accomplish something.
Three Ways to Execute Commands in Python
To execute a Python command, we can type it out on the command line, use the Python interactive shell, or use a script. The last option is where serious work gets done, and it’s what we’ll be using for our full-scale example.
#1. Executing Python Commands from the Command Line
The simplest way to test out Python is to execute a simple “print” statement from the command line like this:
python3 -c 'print("Hello, world!")'
This will generate the following output:
Simple, right? But you can use the command line to even execute complex mathematical operations like this:
python3 -c 'import math; print(math.exp(3) * math.sin(math.radians(45)) - math.log(42, 10))'
The above command imports the “math” library and then prints the result of a sophisticated calculation. Note that the two commands – the import and the print command – are separated by a semicolon (;). This isn’t necessary when you’re executing commands in a script.
#2. Using the Python Interactive Shell to Run Commands
If you have a lot of Python commands to execute one after the other and don’t want to invoke the “python3” command constantly, you can use an interactive shell to save time. Here’s how it works.
To open the Python shell, just type the Python command. So either “python” or “python3”. This will initiate a prompt starting with “>>>”, and you can input your Python commands without prefixing them like this:
So if you have a number of Python commands that you want to run, it’s easier to open the Python shell and input them one by one without any preamble. If you’re doing something that requires changing the working directory, it’s likely that you want to do a lot more than that. Maybe update some files or something, so it’s better to use the Python shell to do it, rather than input the commands directly from the command line.
#3. Executing Commands in a File
This is where most serious work in Python gets done. A python script is a file ending with the extension “.py”, and contains Python commands. Despite being interpreted, and despite the term “Python scripts”, python isn’t as limited as a scripting language. In fact, it’s a full-blown programming language, capable of amazing complexity. If you only use Python from the command line, or from the Python interpreter, you’re missing out on what makes Python so great.
So back to changing a directory in Python. Now that we know when we can use Python as a programming, and not just a scripting language, here’s some code to demonstrate how to change a directory using Python, and display the output:
import os # This line imports the os module
# Print the current working directory
print("Current Working Directory: " + os.getcwd())
# Specify the new directory you want to change to
new_directory = "/home/bhagwad/test"
try:
# Change the current working directory
os.chdir(new_directory)
# Print the new current working directory
print("New Working Directory: " + os.getcwd())
except FileNotFoundError:
print("Error: That directory does not exist")
except PermissionError:
print("Error: You do not have permissions to change to that directory")
except Exception as e:
print(f"An error occurred: {e}")
I save this code into a file called “pythonscript.py”, and execute it like this:
python3 pythonscript.py
This gives me the following output:
Not that this doesn’t change the directory of the bash command line. When you change the directory using a Python script, it just means that the process’s working directory has changed and that any operations Python performs with files will apply to the new directory. When the script completes processing, you’ll be dropped back into the same directory from which you executed the script.
Unlike with bash, you don’t need to create any special execute permissions to run the script since it’s not bash, but the python process that’s running it. Note how, in the script, I first imported the “os” module. This module interfaces with the underlying operating system, abstracting away the differences between them, and allows you to change directories in Python in the same way across all platforms, without bothering about the local niceties. So the code above would work the same in Windows as well as Linux.
Also, note that I use a “try” block to run the code and catch potential errors. This is another demonstration of how Python is more of a traditional programming language, than just a scripting language.
Conclusion
As you can see, changing a directory using Python is easy and intuitive once you read the code. It doesn’t make much sense to do so from a bash or Windows command line, but once you paste the code into a script and run it, you can see how useful it can be. The ability of Python to work across all operating systems is a key reason for its popularity, and being able to change the directory is just one example.
I hope you found the tutorial useful!
I’m a NameHero team member, and an expert on WordPress and web hosting. I’ve been in this industry since 2008. I’ve also developed apps on Android and have written extensive tutorials on managing Linux servers. You can contact me on my website WP-Tweaks.com!
Leave a Reply