• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
NameHero® Blog

NameHero® Blog

Web Hosting Tips & Resources From NameHero

  • AI Agents
    • OpenClaw
    • Claude Code
    • n8n
    • Hermes Agent
    • Open WebUI
    • Docker
  • Hosting
    • Web Hosting
    • WordPress Hosting
    • WooCommerce Hosting
    • Enterprise Hosting
    • Email Hosting
    • HeroicGuard
    • GPU Hosting
    • Website Builder
  • VPS
    • Managed VPS
    • Unmanaged VPS
    • Flex VPS
  • Reseller
  • Gaming
  • Domains
  • Account
  • Blog Home
  • Categories
  • Authors

How To Change A Directory In Python

Bhagwad Park

Published on: January 24, 2024

Categories: Linux Command Line, VPS Hosting, Website Development 0

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.

Table of Contents
  • Check if you Have Python Installed
  • Changing the Directory in Python
  • Three Ways to Execute Commands in Python
    • #1. Executing Python Commands from the Command Line
    • #2. Using the Python Interactive Shell to Run Commands
    • #3. Executing Commands in a File
  • Conclusion

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:

Check if Python is Installed
Check if Python is Installed

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:

Executing a Python Command from the Command Line
Executing a Python Command from the Command Line

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:

Python Interactive Shell
Python Interactive Shell

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:

Change the Directory With Python
Change the Directory With Python

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!

Bhagwad Park Profile Picture
Bhagwad Park

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!

Related Posts

Using the “whois” Command – All you Need to Know

If you want to know about who owns a domain, or when it expires, then you need to use the "whois" command. Here's all you need to know.

How to Use Git Rebase Interactive to Manage Commits

As a project progresses, commits can get messy. The git rebase interactive feature allows you to keep a clean commit history.

How to Tar and Gzip a Folder

Here's how to archive and compress a folder so that it's easy to move it from one location to another - In both Linux AND Windows!

Differentiating the df vs du Commands in Linux

Both df and du are Linux commands for estimating disk usage, but they differ in their focus. Df stands for “disk free”, and du stands for disk usage. The first shows the amount of free space available on a volume, and the second shows the amount of space used by specific directories. Both commands have […]

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow & Subscribe

Exclusive promos, content and more!


Most Popular Posts

NameHero’s Recommended WordPress Plugin and Theme Setup

WordPress Hosting vs. Web Hosting – What’s The Difference?

How To Increase The InnoDB Buffer Pool Size

How To Fix A Stuck All-in-One WP Migration Import

How To Add A Subdomain In Cloudflare

Top Categories

  • WordPress
  • WordPress Tutorials
  • OpenClaw Hosting
  • Enterprise Hosting
  • WooCommerce
  • Web Hosting
  • Resellers
  • Website Security
  • Website Development
  • Website Performance
  • VPS Hosting
  • SEO Tips
  • Announcements
  • Domain Registration
NameHero

NameHero® proudly provides web hosting to over 40,000 customers with 99.9% uptime to over 750,000 websites.

  • Master Card
  • Visa
  • American Express
  • Discover
  • Paypal
Products
  • Web Hosting
  • Managed VPS Hosting
  • Unmanaged VPS Hosting
  • Flex VPS Hosting
  • WordPress Hosting
  • WooCommerce Hosting
  • Reseller Hosting
  • Enterprise Hosting
  • GPU Hosting
  • Email Hosting
  • HeroicGuard
  • Domains
  • Website Builder
  • AI Agent Hosting
Help & Support
  • NameHero Blog
  • NameHero Gaming Blog
  • Support
  • Help Center
  • Migrations
  • Affiliates
  • Gaming Affiliates
  • Call 1-855-984-6263
Company
  • About Us
  • Contact Sales
  • Reviews
  • Uptime
  • We're Hiring

Copyright © 2026 Name Hero, LLC. All rights reserved.
NameHero® is a registered trademark.

  • Privacy Policy
  • Terms of Use
  • Acceptable Use Policy
  • Payment Policy
  • DMCA