Python os.chdir() not working with path with spaces and special characters

  operating-system, python

I’m trying to run some files sequentially (scrape.py, tag.py, save.py and select.py) that are located in a folder named ‘cargen’. However, when I try to make os.chdir(path) to access this ‘cargen’ folder, I’m getting an Exception message because in the path to ‘cargen’ folder there’s a directory with spaces and special characters on it.

The code to run the files sequentially looks like the following:

import os
path = "C:/Users/Desktop/repl/Special Cháracters/carcon/"

os.chdir(path)

directory = 'C:/Users/Desktop/scrap/'

files = ['scrape', 'tag', 'save', 'select']

if __name__ == '__main__':
    if not os.path.isdir(directory):
        os.mkdir(directory)

    [os.system('python ' + path + f'{file}.py ' + directory) for file in files]

The message that I’m getting looks like this:

python: can't open file 'C:/Users/Desktop/repl/Special': [Errno 2] No such file or directory

I’ve tried to move to files to a path where there aren’t any special characters or spaces in the path and the code works perfectly. Could anybody please help me with this? How should I define the path to ‘cargen’ to be able to access these files?

NOTE: I’m using Windows 10 with Anaconda

Source: Python Questions

LEAVE A COMMENT