PyODPSは、ファイルリソースとテーブルリソースの2種類のリソースをサポートしています。 このトピックでは、PyODPSのリソースに対して実行できる一般的な操作について説明します。
基本操作
list_resources()
: プロジェクト内のすべてのリソースを照会します。exist_resource()
: リソースが存在するかどうかを確認します。delete_resource()
: リソースを削除します。drop()
メソッドを呼び出して、リソースを削除することもできます。create_resource()
: リソースを作成します。open_resource()
: リソースを読み取ります。
ファイルリソースの管理
共通に加えてファイルファイルリソースには、. pyファイル,. 瓶ファイル、およびアーカイブファイルを作成します。
ファイルリソースの作成
ファイルリソースを作成するには、リソース名、ファイルタイプ、およびファイルのようなオブジェクトまたは文字列を指定して
create_resource()
メソッドを呼び出します。# Use a file-like object to create a file resource. Files such as compressed packages must be read in binary mode. resource = o.create_resource('test_file_resource', 'file', file_obj=open('/to/path/file', 'rb')) # Use a string to create a file resource. resource = o.create_resource('test_py_resource', 'py', file_obj='import this')
ファイルリソースの読み取りと変更
次のいずれかの方法を使用してリソースを開くことができます。
ファイルリソースの
open
メソッドを呼び出して開きます。MaxComputeエントリオブジェクトの
open_resource()
メソッドを呼び出します。
開かれたオブジェクトはファイルライクオブジェクトです。 ファイルリソースのオープンモードは、Pythonで定義されている
open()
メソッドに似ています。 ファイルリソースのオープンモードの例を次に示します。with resource.open('r') as fp: # Open a resource in read mode. content = fp.read() # Read all content. fp.seek(0) # Return to the beginning of the resource. lines = fp.readlines() # Read multiple lines. fp.write('Hello World') # Error. Data cannot be written in read mode. with o.open_resource('test_file_resource', mode='r+') as fp: # Open the file in read/write mode. fp.read() fp.tell() # Locate the current position. fp.seek(10) fp.truncate() # Truncate the file to the specified length. fp.writelines(['Hello\n', 'World\n']) # Write multiple lines into the file. fp.write('Hello World') fp.flush() # Manually call the method to submit the update to MaxCompute.
PyODPSは次のオープンモードをサポートします。
r
: 読み取りモード。 ファイルを開くことはできますが、データを書き込むことはできません。w
: 書き込みモード。 ファイルにデータを書き込むことはできますが、ファイル内のデータを読み取ることはできません。 ファイルが書き込みモードで開かれた場合、ファイルの内容は最初にクリアされます。a
: 追加モード。 ファイルの最後にデータを追加できます。r +
: 読み取り /書き込みモード。 このモードでは、ファイルからデータを読み書きできます。w +
: このモードはr +
モードに似ています。 唯一の違いは、ファイルの内容が最初にクリアされることです。a +
: このモードはr +
モードに似ています。 唯一の違いは、ファイルの最後にしかデータを書き込むことができないことです。
PyODPSは、圧縮ファイルなどの一部のファイルリソースに対して、次のバイナリオープンモードもサポートしています。
rb
: バイナリ読み取りモード。r + b
: バイナリ読み取り /書き込みモード。
テーブルリソースの管理
テーブルリソースの作成
o.create_resource('test_table_resource', 'table', table_name='my_table', partition='pt=test')
テーブルリソースの更新
table_resource = o.get_resource('test_table_resource') table_resource.update(partition='pt=test2', project_name='my_project2')
テーブルとパーティションに関する情報を取得する
table_resource = o.get_resource('test_table_resource') table = table_resource.table print(table.name) partition = table_resource.partition print(partition.spec)
データの読み取りと書き込み
table_resource = o.get_resource('test_table_resource') with table_resource.open_writer() as writer: writer.write([0, 'aaaa']) writer.write([1, 'bbbbb']) with table_resource.open_reader() as reader: for rec in reader: print(rec)