当前位置: 动力学知识库 > 问答 > 编程问答 >

Get arbitrary resources content in Python 3

问题描述:

I need to get the content of the resources received in command line. The user can write a relative path to a file or an URL. Is it possible to read from this resource regardless if it is a path to a file or an URL?

In Ruby I have something like the next, but I'm having problems finding a Python alternative:

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

网友答案:

I don't know of a nice way to do it, however, urllib.request.urlopen() will support opening normal URLs (http, https, ftp, etc) as well as files on the file system. So you could assume a file if the URL is missing a scheme component:

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()

This works for the following user input:

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

Note that file: (without slashes) might not be a valid URI, however, this is the only way to open a file specified by relative path, and urlopen() works with such URIs.

分享给朋友:
您可能感兴趣的文章:
随机阅读: