ryan9025
ryan9025

Reputation: 269

CMD Create a new folder but "The filename, directory, or volume syntax is incorrect"

I tried to use Python to run the following command lines. The first command line can always work, but the second one cannot and I don't know why.

import os, sys

os.system('IF EXIST C:\APC (echo 1) else (mkdir C:\APC)')

os.system('IF EXIST C:\APC\3d (echo 1) else (mkdir C:\APC\3d)')

If anyone knows the answer, pls let me know thanks!

Upvotes: 1

Views: 70

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

this works by sheer luck:

os.system('IF EXIST C:\APC (echo 1) else (mkdir C:\APC)')

because the backslashes don't escape anything (\A isn't an escape sequence)

But just paste the second command in a python REPL and see:

>>> 'IF EXIST C:\APC\3d (echo 1) else (mkdir C:\APC\3d)'
'IF EXIST C:\\APC\x03d (echo 1) else (mkdir C:\\APC\x03d)'

backslashed digits are interpreted as the actual byte value... Using raw string prefix fixes that:

>>> r'IF EXIST C:\APC\3d (echo 1) else (mkdir C:\APC\3d)'
'IF EXIST C:\\APC\\3d (echo 1) else (mkdir C:\\APC\\3d)'

but don't call system commands to test & create dirs. Use pure python to do that:

import os

d = r"C:\APC\3d"
if os.path.exists(d):
    print("exists")
else:
    os.mkdir(d)

It's more readable, easier to debug, you benefit of python exceptions and makes your code more portable on other platforms (well, not with that hardcoded path of course)

Upvotes: 3

Related Questions