pythonoracle-cloud-infrastructureoci-python-sdk

python oci: Oracle Cloud Infrastructure: How to list files in a bucket


I am trying to print the files in a bucket on Oracle cloud. I have installed oci library for it and came this far. Now I dont know further how to get list of files in a particular bucket.

import os,oci
from oci.config import validate_config

tenancyId="sdkfh" # Your tenancies OCID.
authUserId="sdjfs"; # The OCID of the user ID being used.
OCI_KEY_PATH="filename"; # Path of the key file.
keyFingerprint="12:13:14:15"; # The fingerprint of the key file being used

config = {
    "user": authUserId,
    "key_file": OCI_KEY_PATH,
    "fingerprint": keyFingerprint,
    "tenancy": tenancyId,
    "region": "us-phoenix-1"
}

validate_config(config)

identity = oci.identity.IdentityClient(config)
user = identity.get_user(config["user"]).data
print(user)

Solution

  • To list the objects inside the bucket.

    import os,oci
    from oci.config import validate_config
    
    tenancyId="sdkfh" # Your tenancies OCID.
    authUserId="sdjfs"; # The OCID of the user ID being used.
    OCI_KEY_PATH="filename"; # Path of the key file.
    keyFingerprint="12:13:14:15"; # The fingerprint of the key file being used
    namespace = "xyz"
    bucket_name = "abc"
    config = {
        "user": authUserId,
        "key_file": OCI_KEY_PATH,
        "fingerprint": keyFingerprint,
        "tenancy": tenancyId,
        "region": "us-phoenix-1"
    }
    #it validates the above fields for connection
    validate_config(config)
    # prefix and fields are optional paramater.
    #prefix is for filename pattern but not a regex
    #fields valid values - md5,name,timeCreated,size
    object_storage_client = oci.object_storage.ObjectStorageClient(config)
    object_list = object_storage_client.list_objects(namespace, bucket_name, prefix = filename , fields="name,timeCreated,size")
    for o in object_list.data.objects:
        print(o.name)
    

    Output: List of files inside the bucket with given fields

    Suppose you want those files which are starting like filename*, than give prefix as filename. As it is not a regex so * and other things will not work. Here, i am not able to get time last modified and various other fields. If someone knows about it please let me know here. Python SDK for Oracle Cloud Infrastructure Github Link to source.