python 七牛云操作 作者:马育民 • 2024-04-06 20:39 • 阅读:10021 ``` import qiniuapi,fvm,global_variable import os, json,traceback # 需要填写你的 Access Key 和 Secret Key access_key = '' secret_key = '' bucket_name = "" bucket_domain = "" print("七牛上传 v0.1") print() print(""" 1. 上传到七牛云 2. 从七牛云下载 3. 查看七牛云文件 """) op = input("请选择操作:") if op == "1": path = input("输入要上传的文件或文件夹路径:") if path.strip() == "": print("请正确输入路径") exit() qiniu_save_dir = input("输入七牛云保存的文件夹:") if qiniu_save_dir.strip() == "": print("请正确输入文件件") exit() if os.path.isdir(path): # 如果是文件件 q = qiniuapi.init(access_key, secret_key) # C:\Users\mym\Desktop\重庆发票\[ID01xvhIKhAAPB].pdf qiniuapi.upload_dir(q,bucket_name,path,qiniu_save_dir) else: q = qiniuapi.init(access_key, secret_key) name = os.path.basename(path) qiniuapi.upload_file(q,bucket_name,path,qiniu_save_dir+"/"+name) elif op == "2": qiniu_dir = input("输入要从七牛云下载的文件夹路径:") local_save_dir = input("输入要保存的本地路径:") q = qiniuapi.init(access_key, secret_key) qiniu_dir = qiniuapi.format_qiniu_dir(qiniu_dir) info = qiniuapi.list_file(q, bucket_name, qiniu_dir) res = json.loads(info.text_body) # print(res.get("items")) for item in res.get("items"): # print(item) # print(item.get("key"), item.get("fsize"), item.get("type"), item.get("status"), item.get("md5"),item.get("putTime")) # 七牛云上的文件名 qiniu_name = qiniuapi.get_name_from_qiniu( item.get("key") ) local_file = local_save_dir + "/" + qiniu_name if os.path.exists(local_file): print("本地存在文件 【",local_file,"】,要继续下载并覆盖本地文件吗?(y:下载并覆盖;n:不下载该文件,继续下载其他文件)") while True: res = input(">") if res == "y": try: qiniuapi.download_file(q, bucket_domain, item.get("key"), local_save_dir) print("下载成功 【",local_file,"】") except: traceback.print_exc() break elif res == "n": break else: print("您输出的不正确,请重新输入(y:下载并覆盖;n:不下载该文件,继续下载其他文件)") elif op == "3": path = input("输入要查看的文件夹路径:") q = qiniuapi.init(access_key, secret_key) info = qiniuapi.list_file(q,bucket_name,path) # print("info.status_code:",info.status_code) # print("info.exception:",info.exception) res = json.loads(info.text_body) # print(res.get("items")) for item in res.get("items"): print(item.get("key"),item.get("fsize"),item.get("type"),item.get("status"),item.get("md5")) else: print("无此操作") ``` 原文出处:http://malaoshi.top/show_1IX7SiUOneBt.html