'Problem in changing directory with a path variable in google colab

I want to change directory in google colab.

a = 'drive/MyDrive/COLAB/colab_common_utilities'

Following works:

# method 1:
import os
os.chdir('drive/MyDrive/COLAB/colab_common_utilities')

# method 2:
%cd 'drive/MyDrive/COLAB/colab_common_utilities'

But following does not:

a = 'drive/MyDrive/COLAB/colab_common_utilities'

# method 1-a:
import os
os.chdir(a)

# method 2-a:
%cd a

I dont want to hardcode the path. What is the right syntax to change the path with a variable?



Solution 1:[1]

So, answer is

import os
os.chdir(a)

I restarted all with -
Runtime/"Restart and run all"

Following were the results:

a = 'drive/MyDrive/COLAB/colab_common_utilities'

# method 2-a:
%cd a
>> [Errno 2] No such file or directory: 'a'
# or
!cd a
>> /bin/bash: line 0: cd: a: No such file or directory


# method 1-a:
import os
os.chdir(a)
!pwd
>> /content/drive/MyDrive/COLAB/colab_common_utilities

Apparently, method 1-a always worked but just needed a total flush with "Restart and run all" and not just "Run all." I regret the oversight.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pranav Joshi