【问题标题】:How to open an XML file with python client for google cloud storage如何使用 python 客户端打开用于谷歌云存储的 XML 文件
【发布时间】:2019-04-16 12:38:45
【问题描述】:

我是个菜鸟,没有其他方法可以解决这个问题,所以我需要用 Python 来解决。我需要解析一个 xml 文件。当文件存储在本地时,这可以正常工作。但是,我需要能够在 Google Cloud Storage 中打开该文件。

请看我的代码。我不知道如何将 blob 作为文件名传递给 ElementTree。如果我使用 blob.download_as_string() 我将 xml 文件的内容作为名称。哪个ofcourse太长而且文件路径错误。

import xml.etree.ElementTree as ET
from google.cloud import storage
client = storage.Client()

#My bucket
bucket = client.get_bucket('import')

# This is my file
blob = bucket.get_blob('/xml/Profit.xml')

xml_file = blob.download_as_string()
#xml_file is now looooong string and not what I want

root = 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 变量包含我存储桶中文件的路径。或者想办法解析文件的内容。

感谢任何为我指明正确方向的建议。

干杯, 危机

【问题讨论】:

    标签: python google-cloud-platform google-cloud-storage


    【解决方案1】:

    读取文件并解析:

    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)
    

    【讨论】:

    • 感谢您帮助我。我收到此错误:模块“cloudstorage”没有属性“打开”。我安装了这个包。
    • ok 我需要启用 appengine 来访问文件吗?我认为安装这个包就足够了github.com/scottwernervt/cloudstorage
    • 谢谢!好的关于如何在解析时使用下载的 blob 的任何建议?
    • 我现在让它工作得很好。我将我的初始代码与您建议的“ET.fromstring(contents)”一起使用,现在我可以解析字符串了。
    猜你喜欢
    • 2016-03-21
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2019-05-08
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多