在sublime text3和IDLE中运行我的Python代码,但结果不一样



我想使用Python检查文件是否存在,C:/test/UpdatePackage/filelist是现有文件。

当在崇高文本3中运行时,结果是错误的:

>>> f = "C:/test/UpdatePackage/filelist"
>>> import os
>>> os.path.isfile(f)
False
>>> 

但在Python 3.4 GUI 中运行

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = "C:/test/UpdatePackage/filelist"
>>> import os
>>> os.path.isfile(f)
True
>>>

除了timgeb的答案:

我还没有尝试过,但os.path.isfile(os.path.normpath(f))应该会给你预期的行为。使用normpath(),则可以使用/作为分隔符,并且您的代码(更)独立于您的平台或解释器(例如,如果您从用户输入或其他来源获得路径)。

在脚本中使用f = "C:\test\UpdatePackage\filelist"。我相信IDLE自动地用os.sep代替了前斜线,这就是它在IDLE中工作的原因。

最新更新