簡體   English   中英

檢查路徑在 Python 中是否有效

[英]Check whether a path is valid in Python

有什么簡單的方法可以檢查路徑是否有效? 該文件現在不必存在,我想知道它是否可以存在。

我目前的版本是這樣的:

try:
  f = open(path)
except:
  <path invalid>

我正在考慮簡單地檢查路徑是否包含這些字符中的任何一個。

您也可以嘗試以下方法:

import os  
if not os.path.exists(file_path):
    print "Path of the file is Invalid"

首先嘗試是最好的方法,我建議這樣做。

try:
    open(filename, 'w')
except OSError:
    # handle error here

我相信你會得到 OSError,明確地捕捉到它,並在你使用它的平台上進行測試。

從 python 3.4 開始,要檢查路徑是否有效,您還可以使用pathlib模塊來執行此操作:

from pathlib import Path

try:
    Path(file_path).resolve()
    exist = True
except (OSError, RuntimeError):
    exist = False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM