用python写一个本地自动上传阿里云盘的代码
时间: 2023-02-28 22:58:31 浏览: 489
首先,你需要安装阿里云的SDK,可以使用pip安装:
```
pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-oss
```
然后,你可以使用下面的代码来实现本地文件的自动上传:
```
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.auth import StsTokenCredential
import oss2
# 阿里云AccessKey ID和AccessKey Secret
access_key_id = "YOUR_ACCESS_KEY_ID"
access_key_secret = "YOUR_ACCESS_KEY_SECRET"
# 阿里云bucket名称和文件名称
bucket_name = "YOUR_BUCKET_NAME"
file_name = "YOUR_FILE_NAME"
# 本地文件路径
local_file = "YOUR_LOCAL_FILE_PATH"
# 使用AccessKey ID和AccessKey Secret初始化客户端
client = AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
# 使用STS Token初始化客户端
credential = StsTokenCredential(access_key_id, access_key_secret, "STS_TOKEN")
auth = oss2.StsAuth(credential)
# 上传文件
bucket = oss2.Bucket(auth, "http://oss-cn-hangzhou.aliyuncs.com", bucket_name)
bucket.put_object_from_file(file_name, local_file)
print("Upload Successful")
```
请将上面代码中的`YOUR_ACCESS_KEY_ID`、`YOUR_ACCESS_KEY_SECRET`、`YOUR_BUCKET_NAME`、`YOUR_FILE_NAME`、`YOUR_LOCAL_FILE_PATH`替换为自己的阿里云信息和本地文件路径,运行代码即可实现自动上传。
阅读全文