文件对象关闭的Python回调

我正在研究自定义文件路径类,该类应始终执行一个函数 写入相应的系统文件及其文件对象之后 关闭。该功能会将文件路径的内容上载到远程位置。 我希望上传功能完全在用户的幕后进行 角度来看,即用户可以像使用其他任何os.pathLike一样使用该类 类并自动获取上传功能。以下的伪代码 参考。

import os

class CustomPath(os.pathLike):
    
    def __init__(self,remote_path: str):
        self._local_path = "/some/local/path"
        self._remote_path = remote_path

    def __fspath__(self) -> str:
        return self._local_path
    
    def upload(self):
        # Upload local path to remote path.

我当然可以处理自动调用上载功能的时间 用户直接调用任何一种方法

但是,我不清楚如何自动调用上载功能 有人使用内置open如下写入文件

custom_path = CustomPath("some remote location")

with open(custom_path,"w") as handle:
    handle.write("Here is some text.")

custom_path = CustomPath("some remote location")

handle = open(custom_path,"w")
handle.write("Here is some text.")
handle.close()

我希望与open函数调用兼容,以便 上传行为将适用于所有第三方文件编写器。是这样的吗 在Python中可能发生的行为?

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...