我將 gitlab 中的 XML 檔案讀入一個變數,然后對它進行一些操作。我需要使用該變數在 gitlab 中重寫檔案。當我使用轉儲時- 它會從檔案中洗掉所有內容。如何從 python 重寫 gitlab 中的 XML 檔案?
import gitlab
import io
import xml.etree.ElementTree as ET
gl = gitlab.Gitlab(
private_token='xxxxx')
gl.auth()
projects = gl.projects.list(owned=True, search='Python')
raw_content = projects[0].files.raw(file_path='9_XML/XML_hw.xml', ref='main')
f = io.BytesIO()
f.write(raw_content)
f.seek(0)
xml_file = ET.parse(f) # read file
..... some manipulations with xml_file
project_id = 111111
project = gl.projects.get(project_id)
f = project.files.get(file_path='9_XML/XML_hw.xml', ref='main')
f.content = ET.dump(xml_file) # IT doesn't rewrite, it deletes everything from the file
f.save(branch='main', commit_message='Update file')
uj5u.com熱心網友回復:
ET.dump不產生回傳值。它只列印到標準輸出。如檔案中所述:
將元素樹或元素結構寫入 sys.stdout。此功能應僅用于除錯。
因此,您最終設定f.content = None.
而不是使用.dump,使用.tostring:
xml_str = ET.tostring(xml_file, encoding='unicode')
f.content = xml_str
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452390.html
