Sharanbr
Sharanbr

Reputation: 355

error changing directory in Python

I need to change directory to my local working directory in windows and then open a file for processing.

Its just a 3 lines code, as below:

import csv
import os
os.chdir('D:\Projects\Initiatives\machine learning\programs\assertion')

The error is as follows:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'D:\Projects\Initiatives\machine learning\programs\x07ssertion'

Notice x07 character that has replaced character x07.

I have a similar code but that goes through fine:

import csv
import os
os.chdir('D:\Projects\Initiatives\machine learning\programs')

with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

The only difference is directory assertion in the problematic code.

I have tried single quoting, double quoting etc. for the chdir directive but nothing helps. I have also tried escaping as \assertion but that is not the issue

Upvotes: 0

Views: 199

Answers (1)

ThunderHorn
ThunderHorn

Reputation: 2035

You have to put the path into a raw string in order to work

os.chdir(r'D:\Projects\Initiatives\machine learning\programs')

\ is the escape char of python so it wont work because python thinks that you are escaping the characters

Upvotes: 2

Related Questions