【问题标题】:Get arbitrary resources content in Python 3在 Python 3 中获取任意资源内容
【发布时间】:2014-10-21 11:34:43
【问题描述】:

我需要获取命令行中接收到的资源的内容。用户可以写入文件或 URL 的相对路径。无论是文件路径还是 URL,是否都可以从该资源中读取?

在 Ruby 中,我有类似下一个的东西,但我在寻找 Python 替代品时遇到了问题:

content = open(path_or_url) { |io| io.read }

【问题讨论】:

  • independently 是什么意思?
  • @laike9m 不分类型

标签: python python-3.x io


【解决方案1】:

我不知道有什么好的方法,但是,urllib.request.urlopen() 将支持打开普通 URL(http、https、ftp 等)以及文件系统上的文件。因此,如果 URL 缺少方案组件,您可以假设一个文件:

from urllib.parse import urlparse
from urllib.request import urlopen

resource = input('Enter a URL or relative file path: ')
if urlparse(resource).scheme == '':
    # assume that it is a file, use "file:" scheme
    resource = 'file:{}'.format(resource)
data = urlopen(resource).read()

这适用于以下用户输入:

http://www.blah.com
file:///tmp/x/blah
file:/tmp/x/blah
file:x/blah     # assuming cwd is /tmp
/tmp/x/blah
x/blah          # assuming cwd is /tmp

请注意,file:(不带斜杠)可能不是有效的 URI,但是,这是打开由 relative 路径指定的文件的唯一方法,urlopen() 可以使用此类 URI .

【讨论】:

  • 就像一个魅力,实际上是一个很好的解决方案。谢谢。
猜你喜欢
  • 2012-12-01
  • 2011-03-10
  • 1970-01-01
  • 2021-09-23
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
相关资源
最近更新 更多