python - 如何访问托管在公共远程服务器(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
)。
先感谢您!
解决方案
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')
推荐阅读
- c++ - std::to_chars 在 MacOS / clang 上编译但不链接
- python-3.x - Raspberry Pi 3 B+ (Buster) 无法控制 Dynamixel AX-12A 与 Raspberry Pi 3 B+ (Buster) 与半双工通信
- r - R中Excel的BETADIST()等价函数
- python - SqlAlchemy 使用 Join 查询两个类
- python - 使用 waitress 作为 Flask 的生产服务器
- python - 如何使用python将行插入csv文件
- python - f2py 链接 quadmath 库?将 ctypes 用于 fortran 包装器?
- python - 单独文件中的类之间的Python 3范围?
- smartsheet-api - 我可以按名称而不是索引引用 Smartsheet 列吗?
- php - 为什么“NOT”按位运算符在 PHP 中显示输出 -1 或负数?