我正在创建一个简单的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
在Python中,使用ElementTree模块:
相关问题 更多 >
编程相关推荐