[英]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? (甚至可能在其他地方?)
(如果問題令人困惑:理論上我的意思是它可能不存在(還))
總的來說,這個問題確實很愚蠢,但是,有一些指針可以幫助您猜測(不確定):
\
或/
放在文件中(兩者都被接受為路徑中的分隔符)\
放在文件中( /
用作路徑中的分隔符)why.would.you.do.this
)如果您仍然渴望獲得更好的信心:
我很抱歉問了這么愚蠢的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.