python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python 编辑oss文件

python脚本编辑oss文件的实现示例

作者:yunson_Liu

本文主要介绍了python脚本编辑oss文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1、安装oss2库

root@ubuntu:~# pip3 install oss2
Collecting oss2
  Downloading oss2-2.18.5.tar.gz (283 kB)
     |████████████████████████████████| 283 kB 6.9 MB/s 
Collecting aliyun-python-sdk-core>=2.13.12
  Downloading aliyun-python-sdk-core-2.15.1.tar.gz (443 kB)
     |████████████████████████████████| 443 kB 67.8 MB/s 
Collecting aliyun-python-sdk-kms>=2.4.1
  Downloading aliyun_python_sdk_kms-2.16.3-py2.py3-none-any.whl (98 kB)
     |████████████████████████████████| 98 kB 8.3 MB/s 
Collecting crcmod>=1.7
  Downloading crcmod-1.7.tar.gz (89 kB)
     |████████████████████████████████| 89 kB 14.3 MB/s 
Collecting pycryptodome>=3.4.7
  Downloading pycryptodome-3.20.0-cp35-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 7.0 MB/s 
Requirement already satisfied: requests!=2.9.0 in /usr/lib/python3/dist-packages (from oss2) (2.22.0)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from oss2) (1.14.0)
Requirement already satisfied: cryptography>=2.6.0 in /usr/lib/python3/dist-packages (from aliyun-python-sdk-core>=2.13.12->oss2) (2.8)
Collecting jmespath<1.0.0,>=0.9.3
  Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB)
Building wheels for collected packages: oss2, aliyun-python-sdk-core, crcmod
  Building wheel for oss2 (setup.py) ... done
  Created wheel for oss2: filename=oss2-2.18.5-py3-none-any.whl size=118170 sha256=cd8f24bb98e8449af56d9df9e826cce691d0527e53420f9c2f14a5b85b059d0c
  Stored in directory: /root/.cache/pip/wheels/b6/af/6a/36f940ed11f11b5e1002f94160a82c3dc35e8a357cedc02bb7
  Building wheel for aliyun-python-sdk-core (setup.py) ... done
  Created wheel for aliyun-python-sdk-core: filename=aliyun_python_sdk_core-2.15.1-py3-none-any.whl size=535318 sha256=83c40a77e365ad83d4b74b43e757c6cea78628e8054706e48ae424ed8ddf7b69
  Stored in directory: /root/.cache/pip/wheels/64/af/7e/b3ec025852e53d69463404a2b281d4587d45ee710cd45d0f38
  Building wheel for crcmod (setup.py) ... done
  Created wheel for crcmod: filename=crcmod-1.7-cp38-cp38-linux_x86_64.whl size=35994 sha256=9fc029c468fe548c4862be3ab4783e1d17b2ba52b72aef537d520b42f1c0a0ad
  Stored in directory: /root/.cache/pip/wheels/ca/5a/02/f3acf982a026f3319fb3e798a8dca2d48fafee7761788562e9
Successfully built oss2 aliyun-python-sdk-core crcmod
Installing collected packages: jmespath, aliyun-python-sdk-core, aliyun-python-sdk-kms, crcmod, pycryptodome, oss2
Successfully installed aliyun-python-sdk-core-2.15.1 aliyun-python-sdk-kms-2.16.3 crcmod-1.7 jmespath-0.10.0 oss2-2.18.5 pycryptodome-3.20.0

2、编写脚本

1)更改后将文件更美观的输出

参数indent=4:以将 JSON 数据格式化为具有缩进的形式,使其更易于阅读。
参数ensure_ascii=False:以确保中文字符能够正确地输出

脚本json格式化输出

import json
import oss2

def update_oss_json_value(access_key_id, access_key_secret, endpoint, bucket_name, file_path, key_value_map):
    # 创建 OSS 客户端
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    # 读取文件内容
    content = bucket.get_object(file_path).read()

    # 解析 JSON
    data = json.loads(content)

    # 修改指定 key 的值
    for key, value in key_value_map.items():
        if key in data:
            data[key] = value

    # 将修改后的 JSON 格式化为美观的字符串
    new_content = json.dumps(data, indent=4, ensure_ascii=False)

    # 上传修改后的文件内容
    bucket.put_object(object_key, new_content.encode('utf-8'))

    print("File content has been updated.")

# 要修改的 OSS 文件路径
file_path = 'test/domain_bak.json'

# 指定正确的 endpoint
endpoint = 'http://oss-cn-hongkong.aliyuncs.com'

# 要修改的 key-value 映射
key_value_map = {
    'superSign1': 'https://uykkr.abc.com/c/gulorex6',
    'superSign2': 'https://dspcs.abc.com/c/xqjqujc2'
}

# 调用函数更新 OSS 文件内容
update_oss_json_value('XXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXX', endpoint, 'test', file_path, key_value_map)

执行后会将json文件格式化输出,如有不是很规范的都会更加美观的显示

2)保持每个键值对都占据一行,并在开头空四格

import json
import oss2

def update_oss_json_value(access_key_id, access_key_secret, endpoint, bucket_name, file_path, key_value_map):
    # 创建 OSS 客户端
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    # 读取文件内容
    content = bucket.get_object(file_path).read()

    # 解析 JSON
    data = json.loads(content)

    # 修改指定 key 的值
    for key, value in key_value_map.items():
        if key in data:
            data[key] = value

    # 将修改后的 JSON 转换为字符串,保持每个键值对都占据一行,并在开头空四格
    new_content = ',\n'.join([f'    "{k}": "{v}"' for k, v in data.items()])

    # 添加大括号,保持 JSON 格式
    new_content = '{\n' + new_content + '\n}'

    # 上传修改后的文件内容
    bucket.put_object(object_key, new_content.encode('utf-8'))

    print("File content has been updated.")

# 要修改的 OSS 文件路径
file_path = 'test/domain_bak.json'

# 指定正确的 endpoint
endpoint = 'http://oss-cn-hongkong.aliyuncs.com'

# 要修改的 key-value 映射
key_value_map = {
    'superSign1': 'https://uykkr.abc.com/c/gulorex6',
    'superSign2': 'https://dspcs.abc.com/c/xqjqujc2'
}

# 调用函数更新 OSS 文件内容
update_oss_json_value('XXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXX', endpoint, 'test', file_path, key_value_map)

3、通过位置参数进行新增键值对

import json
import oss2
import argparse

def update_oss_json_value(access_key_id, access_key_secret, endpoint, bucket_name, file_path, *superSigns):
    # 创建 OSS 客户端
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    # 读取文件内容
    content = bucket.get_object(file_path).read()

    # 解析 JSON
    data = json.loads(content)

    # 生成 key-value 映射
    key_value_map = {}
    for i, superSign in enumerate(superSigns, start=1):
        key = f'superSign{i}'
        key_value_map[key] = superSign

    # 修改指定 key 的值
    for key, value in key_value_map.items():
        #if key in data:
        data[key] = value
        print(key,value)

    # 将修改后的 JSON 转换为字符串,保持每个键值对都占据一行,并在开头空四格
    new_content = ',\n'.join([f'    "{k}": "{v}"' for k, v in data.items()])

    # 添加大括号,保持 JSON 格式
    new_content = '{\n' + new_content + '\n}'

    # 打印更新后的键值对
    for key, value in data.items():
        print(f"{key}: {value}")
             
    # 上传修改后的文件内容
    bucket.put_object(file_path, new_content.encode('utf-8'))

    print("File content has been updated.")

if __name__ == "__main__":
    # 创建参数解析器
    parser = argparse.ArgumentParser(description="Update OSS JSON file")

    # 添加命令行参数
    #parser.add_argument("access_key_id", type=str, help="Access Key ID")
    #parser.add_argument("access_key_secret", type=str, help="Access Key Secret")
    #parser.add_argument("endpoint", type=str, help="OSS Endpoint")
    parser.add_argument("bucket_name", type=str, help="Bucket Name")
    parser.add_argument("file_path", type=str, help="Object Key")
    parser.add_argument("superSigns", nargs='+', type=str, help="Values for superSigns")

    # 解析命令行参数
    args = parser.parse_args()

    # 调用函数更新 OSS 文件内容
    update_oss_json_value('XXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXX', 'http://oss-cn-hongkong.aliyuncs.com', args.bucket_name, args.file_path, *args.superSigns)

执行

root@ubuntu:~# python3 kong.py 'test-prod' 'test/domain_bak.json' 'https://uykkr.abc.com/api/c/gulorex6' 'https://dspcs.abc.com/api/c/xqjqujc2'
superSign1 https://uykkr.abc.com/api/c/gulorex6
superSign2 https://dspcs.abc.com/api/c/xqjqujc2
。。。。。文本json。。。。。
File content has been updated. 
root@ubuntu:~# python3 kong.py 'test-prod' 'test/domain_bak.json' 'https://uykkr.abc.com/api/c/gulorex6' 'https://dspcs.abc.com/api/c/xqjqujc2' 'https://dspcs.abc.com/api/c/acrik5'
superSign1 https://uykkr.abc.com/api/c/gulorex6
superSign2 https://dspcs.abc.com/api/c/xqjqujc2
superSign3 https://dspcs.abc.com/api/c/acrik5
。。。。。文本json。。。。。
File content has been updated.
root@ubuntu:~# python3 kong.py 'test-prod' 'test/domain_bak.json' 'https://uykkr.abc.com/api/c/gulorex6' 'https://dspcs.abc.com/api/c/xqjqujc2' 'https://dspcs.abc.com/api/c/acrik5' 'https://dspcs.abc.com/api/c/acrik5'
superSign1 https://uykkr.abc.com/api/c/gulorex6
superSign2 https://dspcs.abc.com/api/c/xqjqujc2
superSign3 https://dspcs.abc.com/api/c/acrik5
superSign4 https://dspcs.abc.com/api/c/acrik5
。。。。。文本json。。。。。
File content has been updated.

到此这篇关于python脚本编辑oss文件的实现示例的文章就介绍到这了,更多相关python 编辑oss文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文