从特定路径加载XML文件

2024-04-20 07:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的GUI应用程序来管理未知单词,同时学习一门新语言。无论如何,我在从特定路径加载XML文件时遇到了问题,因为我不知道如何正确声明文件路径。程序应该首先声明文件路径,检查目录是否存在并在必要时创建它,检查文件(XML文档)是否存在并在必要时创建它,写入开始和结束元素,最后从指定的路径加载XML文档。你知道吗

在C和Windows中,我会这样做:

string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string vocabulary_path = path + "\\Vocabulary\\Words.xml";

if (!Directory.Exists(path + "\\Vocabulary"))
    Directory.CreateDirectory(path + "\\Vocabulary");

if (!File.Exists(vocabulary_path))
{
    XmlTextWriter xW = new XmlTextWriter(vocabulary_path, Encoding.UTF8);
    xW.WriteStartElement("Words");
    xW.WriteEndElement();
    xW.Close();
}

XmlDocument xDoc = new XmlDocument();
xDoc.Load(vocabulary_path);

…但我用的是Python和Linux。你知道吗

到目前为止,我掌握的情况如下:

if not os.path.exists(directory):
    os.makedirs(directory)

my_file = Path("/path/to/file")

if not my_file.is_file():
    # create an XML document and write start and end element into it

Tags: 文件path文档路径声明stringifenvironment
1条回答
网友
1楼 · 发布于 2024-04-20 07:36:36

在Python中,使用ElementTree模块:

import os
import xml.etree.ElementTree as et

vocabulary = os.path.join(path, "Vocabulary", "Words.xml")

if not os.path.exists(vocabulary):
    if not os.path.exists(os.path.dirname(vocabulary)):
        os.mkdirs(os.path.dirname(vocabulary))
    doc = et.Element('Words')
    tree = et.ElementTree(doc)
    tree.write(vocabulary)
else:
    tree = et.ElementTree(file=vocabulary)

相关问题 更多 >