首页 > 解决方案 > 如何访问托管在公共远程服务器(python)上的文件?

问题描述

我想在我的 python 脚本中读取的 tsv 文件托管在http://afakesite.org/myfile.tsv(手动访问 URL 会启动文件的下载,但我想将它保留在服务器上)。

我希望能够从 python 脚本中读取此文件(例如托管在 colab 或 github 上,因此无需下载文件),但我没有找到资源来执行此操作。

f = open("http://afakesite.org/myfile.tsv", "r", encoding="utf8")不起作用(返回 a [Errno 2] No such file or directory)。

先感谢您!

标签: python

解决方案


urllib.request.urlopen就像open,但对于 URL:

from urllib.request import urlopen
with urlopen("http://afakesite.org/myfile.tsv") as f:
    # read f like a file object

请注意,该对象产生字节,即其​​行为类似于以二进制模式打开的文件。因此,您不能逐行读取它,而是以一定大小的块读取。

如果文件不是太大,你可以一次读完:

lines = f.read().decode('utf-8').split('\n')

推荐阅读