最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

引言

在本篇博客中,我們將學(xué)習(xí)如何使用 wxPython 構(gòu)建一個(gè)簡(jiǎn)單的文件復(fù)制工具,并將文件路徑和目標(biāo)目錄的配置信息保存到 XML 文件中。通過(guò)這種方式,我們可以在下次運(yùn)行程序時(shí)輕松加載之前保存的配置。
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)建一個(gè) wxPython 應(yīng)用程序,包含以下幾個(gè)組件:

  • 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. 實(shí)現(xiàn)功能

我們需要實(shí)現(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 文件保存和加載配置。每個(gè)配置包括一個(gè)名稱(chēng)、文件路徑列表和目標(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. 運(yùn)行程序

最后,運(yùn)行程序:

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

結(jié)果如下

總結(jié)

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

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

相關(guān)文章

最新評(píng)論

美姑县| 孙吴县| 若羌县| 青河县| 佛冈县| 徐汇区| 嘉定区| 汪清县| 德保县| 怀仁县| 大化| 洛川县| 宝应县| 洪江市| 富阳市| 河北省| 巧家县| 德化县| 哈巴河县| 龙州县| 瑞安市| 什邡市| 宝清县| 芒康县| 唐山市| 洪江市| 昌黎县| 惠来县| 台湾省| 白山市| 京山县| 博野县| 洪泽县| 荣成市| 乌兰浩特市| 周口市| 锦屏县| 长乐市| 贵港市| 开江县| 子洲县|