有没有简单的方法来检查路径是否有效?该文件现在不必存在,我想知道它是否存在.
我目前的版本是这样的:
try:
f = open(path)
except:
<path invalid>
Run Code Online (Sandbox Code Playgroud)
我正在考虑简单地检查路径是否包含任何这些字符.
您也可以尝试以下方法:
import os
if not os.path.exists(file_path):
print "Path of the file is Invalid"
Run Code Online (Sandbox Code Playgroud)
首先尝试是最好的方法,我建议这样做。
try:
open(filename, 'w')
except OSError:
# handle error here
Run Code Online (Sandbox Code Playgroud)
我相信您会收到 OSError,显式捕获它,并在您使用它的平台上进行测试。