简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM