简体   繁体   English

Python程序可以在网络上打开文本文件吗?

[英]Can A Python Program Open An Text File On The Web?

I am making a program, and was wondering if a .txt file can be hosted on the web and be accessed by the open() function. 我正在编写一个程序,想知道.txt文件是否可以托管在Web上并可以通过open()函数访问。 Does anyone know about this? 有人知道吗?

You can't use open() , but you could use the requests library to do it. 您不能使用open() ,但是可以使用requests库来完成。

import requests

url_to_txt_file = ""
print(requests.get(url_to_txt_file).text)

Alternatively, you could use urllib.request . 另外,您可以使用urllib.request

import urllib.request

url_to_txt_file = ""
print(urllib.request.urlopen(url_to_txt_file).read())

urllib2 can return a file-like object from a URL. urllib2可以从URL返回类似文件的对象。 Here is an example from the documentation : 这是文档中的示例:

>>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read(100)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?xml-stylesheet href="./css/ht2html

There is even the option to build an 'opener' if you really must use the open method: 如果您确实必须使用open方法,甚至可以选择构建“ opener”:

proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM