【问题标题】:pythonic way to identify a local file or a urlpythonic方法来识别本地文件或url
【发布时间】:2023-04-05 15:31:01
【问题描述】:

网址

http://www.example.com
www.example.com
http://example.com
https://example.com

本地文件

file:///example.html
/home/user/example.html
./home/user/example.html
.dir/data/example.html

考虑上述输入并确定给定的输入字符串是本地常规文件还是 URL?

我尝试了什么

import os
from urllib.parse import urlparse

def is_local(_str):
    if os.path.exists(path1):
        return True
    elif urlparse(_str).scheme in ['','file']:
        return True
    return False

打电话

is_local('file:///example.html')     # True
is_local('/home/user/example.html')  # True
is_local('./home/user/example.html') # True
is_local('.dir/data/example.html')   # True

is_local('http://www.example.com')   # False
is_local('www.example.com')          # True
is_local('http://example.com')       # False
is_local('https://example.com')      # False

是否有任何pythonic方法可以在不使用urllib的情况下识别文件是本地文件还是URL?

【问题讨论】:

  • www.example.com 不是 URL,但它可能是本地文件。同样,file:///example.html 是指向本地文件的 URL。这个问题没有很好的定义。
  • @DYZ 是的,可能有没有 urllib 的任何其他 pythonic 方式来做到这一点
  • 什么?正如我所说,你的问题问错了。
  • @DYZ 是的,我修改了问题
  • 本地文件实际上是文件还是只是假设的路径?如果它们是您可以使用的文件,则使用os.path.exists(),如果不是,则假定它是一个远程文件。

标签: python python-3.x file filesystems


【解决方案1】:

您可以使用urllib.parse.urlpathos.path.exisis 的组合。第一个从 URL 中提取文件路径,第二个检查路径是否实际引用文件。

from urllib.parse import urlparse
from os.path import exists

def is_local(url):
    url_parsed = urlparse(url)
    if url_parsed.scheme in ('file', ''): # Possibly a local file
        return exists(url_parsed.path)
    return False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 2014-11-07
    • 2012-11-06
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多