CMD创建一个新文件夹,但“文件名,目录或卷语法不正确”。 [英] CMD Create a new folder but "The filename, directory, or volume syntax is incorrect"

查看:162
本文介绍了CMD创建一个新文件夹,但“文件名,目录或卷语法不正确”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Python运行以下命令行。第一个命令行始终可以工作,但是第二个命令行却不能,我也不知道为什么。

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!

推荐答案

这完全是靠运气:

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

因为反斜杠不能逃脱任何内容( \A 不是转义序列)

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

但是只需将第二个命令粘贴到python REPL中,然后查看:

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)'

但不要不会调用系统命令进行测试和测试创建目录。使用纯python来做到这一点:

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)

它更具可读性,更易于调试,您从python异常中受益,并使您的代码在其他平台上更具可移植性(嗯,不是那样)硬编码路径)

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)

这篇关于CMD创建一个新文件夹,但“文件名,目录或卷语法不正确”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆