TOSFS 是一个轻量级的访问TOS 的 Python SDK,用户可以直接在纯Python环境中使用它。
说明
建议使用3.9及以上版本的Python环境。
通过如下命令安装TOSFS的最新版本。
pip install tosfs
以下示例为使用TosFileSystem的常用API读写TOS。
import os from tosfs.core import TosFileSystem # init TosFileSystem fs = TosFileSystem( endpoint_url="https://{your-tos-endpoint}", key="{your-access-key}", secret="{your-secret-key}", region="{your-region}" ) local_file_path = "localfile.txt" remote_file_path = "tos://{your-bucket}/remote_file.txt" # create a local file to upload with open(local_file_path, "w") as f: f.write("Hello TOSFS.") # upload to tos fs.put_file(local_file_path, remote_file_path) print(f"Uploaded {local_file_path} to {remote_file_path}") # download from tos downloaded_file_path = "downloaded_file.txt" fs.get_file(remote_file_path, downloaded_file_path) print(f"Downloaded {remote_file_path} to {downloaded_file_path}") # read content from downloaded local file with open(downloaded_file_path, "r") as f: content = f.read() print(f"Content of {downloaded_file_path}: {content}") # delete tos file fs.rm(remote_file_path) # write to tos with fs.open(remote_file_path, "w") as f: f.write("Hello TOSFS.") # read from tos with fs.open(remote_file_path, "r") as f: tos_content = f.read() print(f"Content of {remote_file_path}: {tos_content}") # clean local files os.remove(local_file_path) os.remove(downloaded_file_path)
适用如上代码时,须将endpoint_url
、key
、secret
、region
变量替换为真实的认证信息。并将本地路径和TOS上的路径替换为真实有效的路径,即可成功运行。