Python: Retrieve the current working directory and change the dir
9. Change Directory Upwards
Write a Python program to retrieve the current working directory and change the dir (move up one).
Sample Solution:
Python Code :
import os
print('Current dir:', os.getcwd())
print('\nChange the dir (moving up one):', os.pardir)
os.chdir(os.pardir)
print('Current dir:', os.getcwd())
print('\nChange the dir (moving up one):', os.pardir)
os.chdir(os.pardir)
print('Current dir:', os.getcwd())
Sample Output:
Current dir: /tmp/sessions/a9c74a8fb247929c Change the dir (moving up one): .. Current dir: /tmp/sessions Change the dir (moving up one): .. Current dir: /tmp
For more Practice: Solve these Related Problems:
- Write a Python program to retrieve the current working directory, change to its parent directory using os.chdir(".."), and then print the new working directory.
- Write a Python script to move one level up from the current directory and list all files and directories in the new location.
- Write a Python function that obtains the current directory, moves up one level, and then returns the new working directory along with its contents.
- Write a Python program to capture the current directory, change to its parent directory, and verify the change by comparing the old and new paths.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find the parent’s process id, real user ID of the current process and change real user ID.
Next: Write a python program to access environment variables and value of the environment variable.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.