簡體   English   中英

Python中如何判斷一個不存在的路徑是否以跨平台的方式通向一個目錄或一個文件?

[英]How to tell if a non-existent path leads to a directory or a file in a cross-platform way in Python?

以下是我目前猜測路徑是否指向理論文件或文件夾的方式:

def __init__(self, path:str, is_dir:bool=None):
    # checks
    if is_dir is None: is_dir = path.endswith('/') or path.endswith('\\') or os.path.isdir(path) or '.' not in path  # guess if path is pointing to a file
    self.is_dir = is_dir
    # note: Because both files and folders can, but don't have to include dots in their names,
    #       this check is just a basic guess.
    #
    #       files without extensions that were not yet created will be recognised as folders
    #       and
    #       folders with dots in their name that were not yet created will be recognised as files
    #
    #       If you know of a better solution to this problem (which I frankly don't think exists),
    #       please implement it here.

有沒有更好的方法適用於類 UNIX 和 Windows? (甚至可能在其他地方?)

(如果問題令人困惑:理論上我的意思是它可能不存在(還))

總的來說,這個問題確實很愚蠢,但是,有一些指針可以幫助您猜測(不確定):

  • 在常見的 Windows 文件系統上,您不能將\/放在文件中(兩者都被接受為路徑中的分隔符)
  • 在最常見的 Linux 文件系統上,但是,您可以將\放在文件中( /用作路徑中的分隔符)
  • 目錄不太可能在其名稱中包含點(Linux 上的“隱藏”目錄不是這種情況,您也可以輕松地將目錄命名為why.would.you.do.this

如果您仍然渴望獲得更好的信心:

  • 您可以根據常見文件擴展名列表檢查路徑(但這仍然只是為您提供猜測)
  • 重新考慮你的人生決定

我很抱歉問了這么愚蠢的問題。

暫無
暫無

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

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