1

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You can also use raw strings (e.g., r'C:\Users\Heinz\Desktop\tc_500').
@Heinz - as I said in my answer, \t is an escape sequence, but \T is not. In the first instance, the literal string you're passing is 'C:\Users\Heinz\Desktop c_500', in the second case it's 'C:\Users\Heinz\Desktop\TC_500'. In nearly all situations (unless you're using a case-sensitive NTFS volume) Windows paths are case-insensitive.
@MattDMo but there are no capitals in my file name, I think in the second case, python may not find my file either.
@Heinz - you already said in your question that the second case worked, which it should. If your current working directory was C:\Users\Heinz\Desktop, and you entered either os.chdir('tc_500') or os.chdir('Tc_500') or os.chdir('tC_500') or os.chdir('TC_500'), all would work, because Windows ignores case in file/directory names.
@Heinz - When you have an escape character in a non-raw string, Python strips the escape sequence out and inserts the literal ASCII value of that sequence in the string before passing it to Windows, and of course Windows doesn't interpret it correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.