欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Python和XML實現(xiàn)文件復(fù)制工具的完整代碼

 更新時間:2024年08月05日 11:12:21   作者:winfredzhang  
在本篇博客中,我們將學(xué)習(xí)如何使用 wxPython 構(gòu)建一個簡單的文件復(fù)制工具,并將文件路徑和目標(biāo)目錄的配置信息保存到 XML 文件中,通過這種方式,我們可以在下次運行程序時輕松加載之前保存的配置,需要的朋友可以參考下

引言

在本篇博客中,我們將學(xué)習(xí)如何使用 wxPython 構(gòu)建一個簡單的文件復(fù)制工具,并將文件路徑和目標(biāo)目錄的配置信息保存到 XML 文件中。通過這種方式,我們可以在下次運行程序時輕松加載之前保存的配置。
C:\pythoncode\new\preparitowork.py

全部代碼

import wx
import os
import shutil
import xml.etree.ElementTree as ET

class FileCopyApp(wx.Frame):
    def __init__(self, parent, title):
        super(FileCopyApp, self).__init__(parent, title=title, size=(600, 500))

        self.config_file = 'file_copy_config.xml'

        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        self.load_saved_configs()

        self.saved_configs = wx.ComboBox(panel, choices=list(self.configs.keys()))
        self.saved_configs.Bind(wx.EVT_COMBOBOX, self.on_load_config)
        vbox.Add(self.saved_configs, flag=wx.EXPAND | wx.ALL, border=10)

        self.listbox = wx.ListBox(panel)
        vbox.Add(self.listbox, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.add_button = wx.Button(panel, label='Add Files')
        self.remove_button = wx.Button(panel, label='Remove Selected')
        hbox1.Add(self.add_button, flag=wx.RIGHT, border=10)
        hbox1.Add(self.remove_button)
        vbox.Add(hbox1, flag=wx.ALIGN_CENTER | wx.BOTTOM, border=10)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        self.path_text = wx.TextCtrl(panel)
        self.browse_button = wx.Button(panel, label='Browse')
        self.copy_button = wx.Button(panel, label='Copy Files')
        hbox2.Add(self.path_text, proportion=1)
        hbox2.Add(self.browse_button, flag=wx.LEFT, border=10)
        hbox2.Add(self.copy_button, flag=wx.LEFT, border=10)
        vbox.Add(hbox2, flag=wx.EXPAND | wx.ALL, border=10)

        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        self.config_name_text = wx.TextCtrl(panel)
        self.save_config_button = wx.Button(panel, label='Save Configuration')
        hbox3.Add(self.config_name_text, proportion=1)
        hbox3.Add(self.save_config_button, flag=wx.LEFT, border=10)
        vbox.Add(hbox3, flag=wx.EXPAND | wx.ALL, border=10)

        panel.SetSizer(vbox)

        self.Bind(wx.EVT_BUTTON, self.on_add_files, self.add_button)
        self.Bind(wx.EVT_BUTTON, self.on_remove_selected, self.remove_button)
        self.Bind(wx.EVT_BUTTON, self.on_browse, self.browse_button)
        self.Bind(wx.EVT_BUTTON, self.on_copy_files, self.copy_button)
        self.Bind(wx.EVT_BUTTON, self.on_save_config, self.save_config_button)

        self.Centre()
        self.Show(True)

    def on_add_files(self, event):
        with wx.FileDialog(self, "Open file(s)", wildcard="All files (*.*)|*.*",
                           style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return

            paths = fileDialog.GetPaths()
            for path in paths:
                self.listbox.Append(path)

    def on_remove_selected(self, event):
        selections = self.listbox.GetSelections()
        for index in reversed(selections):
            self.listbox.Delete(index)

    def on_browse(self, event):
        with wx.DirDialog(self, "Choose a directory", style=wx.DD_DEFAULT_STYLE) as dirDialog:
            if dirDialog.ShowModal() == wx.ID_CANCEL:
                return

            self.path_text.SetValue(dirDialog.GetPath())

    def on_copy_files(self, event):
        target_dir = self.path_text.GetValue()
        if not os.path.isdir(target_dir):
            wx.MessageBox('Please select a valid directory', 'Error', wx.OK | wx.ICON_ERROR)
            return

        for i in range(self.listbox.GetCount()):
            file_path = self.listbox.GetString(i)
            if os.path.isfile(file_path):
                shutil.copy(file_path, target_dir)

        wx.MessageBox('Files copied successfully', 'Info', wx.OK | wx.ICON_INFORMATION)

    def on_save_config(self, event):
        config_name = self.config_name_text.GetValue().strip()
        if not config_name:
            wx.MessageBox('Please enter a name for the configuration', 'Error', wx.OK | wx.ICON_ERROR)
            return

        file_paths = [self.listbox.GetString(i) for i in range(self.listbox.GetCount())]
        target_dir = self.path_text.GetValue()

        self.configs[config_name] = {'files': file_paths, 'target_dir': target_dir}
        self.save_configs_to_xml()
        self.saved_configs.Append(config_name)
        wx.MessageBox('Configuration saved successfully', 'Info', wx.OK | wx.ICON_INFORMATION)

    def on_load_config(self, event):
        config_name = self.saved_configs.GetValue()
        config = self.configs.get(config_name)

        if config:
            self.listbox.Clear()
            for file_path in config['files']:
                self.listbox.Append(file_path)

            self.path_text.SetValue(config['target_dir'])

    def load_saved_configs(self):
        self.configs = {}
        if os.path.exists(self.config_file):
            tree = ET.parse(self.config_file)
            root = tree.getroot()
            for config in root.findall('config'):
                name = config.get('name')
                files = [file.text for file in config.findall('file')]
                target_dir = config.find('target_dir').text
                self.configs[name] = {'files': files, 'target_dir': target_dir}

    def save_configs_to_xml(self):
        root = ET.Element('configs')
        for name, data in self.configs.items():
            config_elem = ET.SubElement(root, 'config', name=name)
            for file_path in data['files']:
                file_elem = ET.SubElement(config_elem, 'file')
                file_elem.text = file_path
            target_dir_elem = ET.SubElement(config_elem, 'target_dir')
            target_dir_elem.text = data['target_dir']

        tree = ET.ElementTree(root)
        tree.write(self.config_file)

if __name__ == '__main__':
    app = wx.App()
    FileCopyApp(None, title='File Copier')
    app.MainLoop()

1. 安裝必要的模塊

首先,我們需要安裝 wxPython 和 lxml 模塊。你可以使用以下命令安裝這些模塊:

pip install wxPython lxml

2. 創(chuàng)建主界面

我們將創(chuàng)建一個 wxPython 應(yīng)用程序,包含以下幾個組件:

  • ListBox 用于顯示文件路徑。
  • 按鈕用于添加和移除文件。
  • 文本框和按鈕用于選擇目標(biāo)目錄。
  • 文本框和按鈕用于保存和加載配置。
import wx
import os
import shutil
import xml.etree.ElementTree as ET

class FileCopyApp(wx.Frame):
    def __init__(self, parent, title):
        super(FileCopyApp, self).__init__(parent, title=title, size=(600, 500))

        self.config_file = 'file_copy_config.xml'

        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        self.load_saved_configs()

        self.saved_configs = wx.ComboBox(panel, choices=list(self.configs.keys()))
        self.saved_configs.Bind(wx.EVT_COMBOBOX, self.on_load_config)
        vbox.Add(self.saved_configs, flag=wx.EXPAND | wx.ALL, border=10)

        self.listbox = wx.ListBox(panel)
        vbox.Add(self.listbox, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.add_button = wx.Button(panel, label='Add Files')
        self.remove_button = wx.Button(panel, label='Remove Selected')
        hbox1.Add(self.add_button, flag=wx.RIGHT, border=10)
        hbox1.Add(self.remove_button)
        vbox.Add(hbox1, flag=wx.ALIGN_CENTER | wx.BOTTOM, border=10)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        self.path_text = wx.TextCtrl(panel)
        self.browse_button = wx.Button(panel, label='Browse')
        self.copy_button = wx.Button(panel, label='Copy Files')
        hbox2.Add(self.path_text, proportion=1)
        hbox2.Add(self.browse_button, flag=wx.LEFT, border=10)
        hbox2.Add(self.copy_button, flag=wx.LEFT, border=10)
        vbox.Add(hbox2, flag=wx.EXPAND | wx.ALL, border=10)

        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        self.config_name_text = wx.TextCtrl(panel)
        self.save_config_button = wx.Button(panel, label='Save Configuration')
        hbox3.Add(self.config_name_text, proportion=1)
        hbox3.Add(self.save_config_button, flag=wx.LEFT, border=10)
        vbox.Add(hbox3, flag=wx.EXPAND | wx.ALL, border=10)

        panel.SetSizer(vbox)

        self.Bind(wx.EVT_BUTTON, self.on_add_files, self.add_button)
        self.Bind(wx.EVT_BUTTON, self.on_remove_selected, self.remove_button)
        self.Bind(wx.EVT_BUTTON, self.on_browse, self.browse_button)
        self.Bind(wx.EVT_BUTTON, self.on_copy_files, self.copy_button)
        self.Bind(wx.EVT_BUTTON, self.on_save_config, self.save_config_button)

        self.Centre()
        self.Show(True)

3. 實現(xiàn)功能

我們需要實現(xiàn)以下功能:

  • 添加文件路徑到 ListBox。
  • 移除選定的文件路徑。
  • 選擇目標(biāo)目錄。
  • 復(fù)制文件到目標(biāo)目錄。
  • 保存和加載配置。
    def on_add_files(self, event):
        with wx.FileDialog(self, "Open file(s)", wildcard="All files (*.*)|*.*",
                           style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return

            paths = fileDialog.GetPaths()
            for path in paths:
                self.listbox.Append(path)

    def on_remove_selected(self, event):
        selections = self.listbox.GetSelections()
        for index in reversed(selections):
            self.listbox.Delete(index)

    def on_browse(self, event):
        with wx.DirDialog(self, "Choose a directory", style=wx.DD_DEFAULT_STYLE) as dirDialog:
            if dirDialog.ShowModal() == wx.ID_CANCEL:
                return

            self.path_text.SetValue(dirDialog.GetPath())

    def on_copy_files(self, event):
        target_dir = self.path_text.GetValue()
        if not os.path.isdir(target_dir):
            wx.MessageBox('Please select a valid directory', 'Error', wx.OK | wx.ICON_ERROR)
            return

        for i in range(self.listbox.GetCount()):
            file_path = self.listbox.GetString(i)
            if os.path.isfile(file_path):
                shutil.copy(file_path, target_dir)

        wx.MessageBox('Files copied successfully', 'Info', wx.OK | wx.ICON_INFORMATION)

4. 保存和加載配置

我們使用 XML 文件保存和加載配置。每個配置包括一個名稱、文件路徑列表和目標(biāo)目錄。

    def on_save_config(self, event):
        config_name = self.config_name_text.GetValue().strip()
        if not config_name:
            wx.MessageBox('Please enter a name for the configuration', 'Error', wx.OK | wx.ICON_ERROR)
            return

        file_paths = [self.listbox.GetString(i) for i in range(self.listbox.GetCount())]
        target_dir = self.path_text.GetValue()

        self.configs[config_name] = {'files': file_paths, 'target_dir': target_dir}
        self.save_configs_to_xml()
        self.saved_configs.Append(config_name)
        wx.MessageBox('Configuration saved successfully', 'Info', wx.OK | wx.ICON_INFORMATION)

    def on_load_config(self, event):
        config_name = self.saved_configs.GetValue()
        config = self.configs.get(config_name)

        if config:
            self.listbox.Clear()
            for file_path in config['files']:
                self.listbox.Append(file_path)

            self.path_text.SetValue(config['target_dir'])

    def load_saved_configs(self):
        self.configs = {}
        if os.path.exists(self.config_file):
            tree = ET.parse(self.config_file)
            root = tree.getroot()
            for config in root.findall('config'):
                name = config.get('name')
                files = [file.text for file in config.findall('file')]
                target_dir = config.find('target_dir').text
                self.configs[name] = {'files': files, 'target_dir': target_dir}

    def save_configs_to_xml(self):
        root = ET.Element('configs')
        for name, data in self.configs.items():
            config_elem = ET.SubElement(root, 'config', name=name)
            for file_path in data['files']:
                file_elem = ET.SubElement(config_elem, 'file')
                file_elem.text = file_path
            target_dir_elem = ET.SubElement(config_elem, 'target_dir')
            target_dir_elem.text = data['target_dir']

        tree = ET.ElementTree(root)
        tree.write(self.config_file)

5. 運行程序

最后,運行程序:

if __name__ == '__main__':
    app = wx.App()
    FileCopyApp(None, title='File Copier')
    app.MainLoop()

結(jié)果如下

總結(jié)

通過這篇博客,我們學(xué)習(xí)了如何使用 wxPython 構(gòu)建一個簡單的文件復(fù)制工具,并將文件路徑和目標(biāo)目錄的配置信息保存到 XML 文件中。我們可以輕松加載和保存配置,使得下次運行程序時可以快速恢復(fù)之前的設(shè)置。這是一個實用的小工具,可以幫助我們更高效地管理文件復(fù)制任務(wù)。希望你能從中學(xué)到一些有用的技巧,并應(yīng)用到自己的項目中。

以上就是使用Python和XML實現(xiàn)文件復(fù)制工具的完整代碼的詳細內(nèi)容,更多關(guān)于Python XML文件復(fù)制工具的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • numpy向空的二維數(shù)組中添加元素的方法

    numpy向空的二維數(shù)組中添加元素的方法

    今天小編就為大家分享一篇numpy向空的二維數(shù)組中添加元素的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • 使用django的ORM框架按月統(tǒng)計近一年內(nèi)的數(shù)據(jù)方法

    使用django的ORM框架按月統(tǒng)計近一年內(nèi)的數(shù)據(jù)方法

    今天小編就為大家分享一篇使用django的ORM框架按月統(tǒng)計近一年內(nèi)的數(shù)據(jù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • linux之文件查找指定文件中包含關(guān)鍵字的行信息方式

    linux之文件查找指定文件中包含關(guān)鍵字的行信息方式

    這篇文章主要介紹了linux之文件查找指定文件中包含關(guān)鍵字的行信息方式,具有很好的參考價值,希望對大家有所幫助。
    2023-06-06
  • flask中過濾器的使用詳解

    flask中過濾器的使用詳解

    這篇文章主要介紹了flask中過濾器的使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Apache,wsgi,django 程序部署配置方法詳解

    Apache,wsgi,django 程序部署配置方法詳解

    這篇文章主要介紹了Apache,wsgi,django 程序部署配置方法,結(jié)合實例形式詳細分析了Linux環(huán)境下Apache,wsgi,django程序部署配置的相關(guān)操作技巧與注意事項,需要的朋友可以參考下
    2019-07-07
  • Python學(xué)習(xí)思維導(dǎo)圖(必看篇)

    Python學(xué)習(xí)思維導(dǎo)圖(必看篇)

    下面小編就為大家?guī)硪黄狿ython學(xué)習(xí)思維導(dǎo)圖(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • 解決python spyder 突然打不開的問題

    解決python spyder 突然打不開的問題

    這篇文章主要介紹了解決python spyder 突然打不開的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-05-05
  • 使用Pygal庫創(chuàng)建可縮放的矢量圖表的操作方法

    使用Pygal庫創(chuàng)建可縮放的矢量圖表的操作方法

    在本文中,我們探討了如何使用Pygal庫創(chuàng)建可縮放的矢量圖表,首先,我們介紹了Pygal的基本概念和安裝方法,然后通過多個示例演示了如何創(chuàng)建各種類型的圖表,包括折線圖、柱狀圖、餅圖、散點圖、雷達圖和地圖等,需要的朋友可以參考下
    2024-05-05
  • 后端開發(fā)使用pycharm的技巧(推薦)

    后端開發(fā)使用pycharm的技巧(推薦)

    這篇文章主要介紹了后端開發(fā)使用pycharm的技巧,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • flask的orm框架SQLAlchemy查詢實現(xiàn)解析

    flask的orm框架SQLAlchemy查詢實現(xiàn)解析

    這篇文章主要介紹了flask的orm框架SQLAlchemy查詢實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12

最新評論