PyODPS主要支援兩種資源類型,即檔案和表。本文為您介紹PyODPS中資源的常見操作。
基本操作
list_resources():列出該專案空間下的所有資源。exist_resource():判斷資源是否存在。delete_resource():刪除資源。也可以通過Resource對象調用drop方法實現。create_resource():建立資源。open_resource():讀取資源。
檔案資源
檔案資源套件括基礎的File類型,以及Py、Jar、Archive類型。
- 建立檔案資源
建立檔案資源可以通過給定資源名、檔案類型和一個file-like的對象(或字串對象)調用
create_resource()來建立。# 使用file-like的對象建立檔案資源,注意壓縮包等檔案需要用二進位模式讀取 resource = o.create_resource('test_file_resource', 'file', file_obj=open('/to/path/file', 'rb')) # 使用字串建立檔案資源 resource = o.create_resource('test_py_resource', 'py', file_obj='import this') - 讀取和修改檔案資源 開啟一個資源有如下兩種方法:
- 對檔案資源調用
open方法。 - 在ODPS入口調用
open_resource()方法。
開啟後的對象是file-like的對象。 類似於Python內建的open()方法,檔案資源也支援開啟的模式,樣本如下。with resource.open('r') as fp: # 以讀模式開啟資源。 content = fp.read() # 讀取全部的內容。 fp.seek(0) # 回到資源開頭。 lines = fp.readlines() # 讀成多行。 fp.write('Hello World') # 報錯,讀模式下無法寫資源。 with o.open_resource('test_file_resource', mode='r+') as fp: # 讀寫入模式開啟資源。 fp.read() fp.tell() # 定位當前位置。 fp.seek(10) fp.truncate() # 截斷後面的內容。 fp.writelines(['Hello\n', 'World\n']) # 寫入多行。 fp.write('Hello World') fp.flush() # 手動調用會將更新提交到ODPS。所有支援的開啟類型包括:
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)