how to remove an entry from my PATH in Python?

Viewed 1983

I know I can use

import os
os.environ['PATH'] += os.pathsep + "C:\\Users\\john\\myprog\\bin"

to add this folder to the (python representation of the) PATH. However, how can I remove an entry from the PATH?

Using :

os.environ.pop('C:\\Users\\john\\myprog\\bin') 

does not work here. Any ideas? Thanks!

1 Answers

os.environ['PATH'] is a str object, it doesn't contain a pop() method.

What you want to do instead is split it, remove the last element and then assign a new str to the os.environ['PATH'] like so:

import os
os.environ['PATH'] += os.pathsep + "C:\\Users\\john\\myprog\\bin"

# do something...

os.environ['PATH'] = os.pathsep.join(os.environ['PATH'].split(os.pathsep)[:-1])

You could do it that way... but I would recommend using sys instead:

import sys
sys.path.append(my_dir)

# do what you need

sys.path.remove(my_dir)
Related