Riyan Nayak
Riyan Nayak

Reputation: 39

Is there a way for a Python program to "cd" to a folder that has a space in it?

I am creating a code editor, and I am trying to create a run feature. Right now I see that the problems come when I encounter a folder with a space in its name. It works on the command line, but not with os.system().

def run(event):
    if open_status_name != False:
        directory_split = open_status_name.split("/")
        for directory in directory_split:
            if directory_split.index(directory) > 2:
                true_directory = directory.replace(" ", "\s")
                print(true_directory)
                data = os.system("cd " + directory.replace(" ", "\s"))
                print(data)

I tried to replace the space with the regex character "\s" but that also didn't work.

Upvotes: 1

Views: 268

Answers (1)

tdelaney
tdelaney

Reputation: 77347

os.system runs the command in a shell. You'd have to add quotes to get the value though: os.system(f'cd "{directory}"'). But the cd would only be valid for that subshell for the brief time it exists - it would not change the directory of your python program. Use os.chdir(directory) instead.

Note - os.chdir can be risky as any relative paths you have in your code suddenly become invalid once you've done that. It may be better to manage your editor's "current path" on your own.

Upvotes: 1

Related Questions