【发布时间】: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