我是個菜鳥,沒有其他方法可以解決這個問題,所以我需要用 Python 來解決。我需要解析一個 xml 文件。當文件存儲在本地時,這可以正常工作。但是,我需要能夠在 Google Cloud Storage 中打開文件。請看我的代碼。我不知道如何將 blob 作為文件名傳遞給 ElementTree。如果我使用 blob.download_as_string() 我將 xml 文件的內容作為名稱。這當然是文件的太長和錯誤的路徑。import xml.etree.ElementTree as ETfrom google.cloud import storageclient = storage.Client()#My bucketbucket = client.get_bucket('import')# This is my fileblob = bucket.get_blob('/xml/Profit.xml')xml_file = blob.download_as_string()#xml_file is now looooong string and not what I wantroot = ET.parse(xml_file)#This doesnt work...result = ''for elem in root.findall('.//LEVEL1/DATA'): mystr = elem.text.replace(" ","").replace("+","").replace("-","") print mystr.replace(" ","").replace("+","").replace("-","")我希望 xml_file 變量包含我存儲桶中文件的路徑?;蛘呦朕k法解析文件的內容。任何為我指明正確方向的建議表示贊賞。
1 回答

慕雪6442864
TA貢獻1812條經(jīng)驗 獲得超5個贊
讀取文件并解析它:
import cloudstorage as gcs
import xml.etree.ElementTree as ET
# The filename argument is specified in the format of YOUR_BUCKET_NAME/PATH_IN_GCS
gcs_file = gcs.open(filename)
contents = gcs_file.read()
gcs_file.close()
root = ET.fromstring(contents)
添加回答
舉報
0/150
提交
取消