Pergunta

I think it's a basic python problem, but I just can't find out why.

I have a file named tc_500 containing some CSV files I want to edit, thus I change the directory in order to edit these files.

import sys, os
os.chdir('C:\Users\Heinz\Desktop\tc_500')
print os.getcwd()

But it turns out this error,

>>> 

Traceback (most recent call last):
  File "C:\Users\Heinz\Desktop\python_test\any_test.py", line 13, in <module>
    os.chdir('C:\Users\Heinz\Desktop\tc_500')
WindowsError: [Error 123] 檔案名稱、目錄名稱或磁碟區標籤語法錯誤。: 'C:\\Users\\Heinz\\Desktop\tc_500'

If I change the code like this,

import sys, os
os.chdir('C:\Users\Heinz\Desktop\TC_500')
print os.getcwd()

It can run without any error.

Why I wouldn't get errors while using capitals instead of the real name of the file?

Foi útil?

Solução

You need to use double back slashes in your path:

os.chdir('C:\\Users\\Heinz\\Desktop\\tc_500')

or single forward slashes:

os.chdir('C:/Users/Heinz/Desktop/tc_500')

The sequence \t is an escape sequence for a tab character, and that is messing up further processing of the string. \T is not an escape sequence. The first back slash escapes the second back slash, allowing for the correct path to be passed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top