非常简单的概念,但我无法弄清楚并且需要一些帮助。我需要检查 Program Files 目录中是否存在文件,因此我有以下内容:
import os
if not os.path.exists('C:/Program Files/file_to_be_found'):
print "ERROR: Not Found!"
else:
#rest of program...
但是我知道我不能这样做。如何在命令中编写路径以接受“程序”和"file"之间的空格?
最佳答案
空间还可以。你可以自由地写斜杠。
if os.path.exists('C:/Program Files'): print 'yes'
if os.path.exists(r'C:\Program Files'): print 'yes'
if os.path.exists('C:\\Program Files'): print 'yes'
以上所有内容无论有没有“r”都可以。
@nneonneo 提醒第二个没有“r”是危险的,因为反斜杠是用来转义的。
关于Python(可能还有其他)- 空格的转义字符是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18593401/