我正在尝试调用a python function它采用绝对路径作为参数,但我要引用的文件位于网络上。
如果不在本地克隆文件,有没有办法可以引用该文件,使 python 认为该文件是本地的?
换句话说,我想将 URL 包装在变量 my_file_path
中,并返回 True
:
os.path.isfile(my_file_path)
请注意,我需要伪造文件系统路径,因为我正在使用的程序中的其他调用需要路径,而不是类似文件的对象(这包括调用 the function I linked 的其他函数)
最佳答案
一个非常好的方法是使用 requests图书馆。您可以使用 stream=True
获取类似文件的对象get
函数的选项:
r = requests.get('https://api.github.com/events', stream=True)
loadmat(r.raw, ...)
如果需要实际路径,可以使用tempfile模块以及:
with tempfile.NamedTemporaryFile() as fd:
r = requests.get('https://api.github.com/events', stream=True)
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
fd.flush()
loadmat(fd.name)
# other code here, where the temp file no longer exists but the data has been read
关于python - 将 URL 包装为文件系统路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429817/