使用Python和XML实现文件复制工具的完整代码
引言
在本篇博客中,我们将学习如何使用 wxPython
构建一个简单的文件复制工具,并将文件路径和目标目录的配置信息保存到 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. 创建主界面
我们将创建一个 wxPython
应用程序,包含以下几个组件:
ListBox
用于显示文件路径。- 按钮用于添加和移除文件。
- 文本框和按钮用于选择目标目录。
- 文本框和按钮用于保存和加载配置。
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. 实现功能
我们需要实现以下功能:
- 添加文件路径到
ListBox
。 - 移除选定的文件路径。
- 选择目标目录。
- 复制文件到目标目录。
- 保存和加载配置。
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 文件保存和加载配置。每个配置包括一个名称、文件路径列表和目标目录。
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()
结果如下
总结
通过这篇博客,我们学习了如何使用 wxPython 构建一个简单的文件复制工具,并将文件路径和目标目录的配置信息保存到 XML 文件中。我们可以轻松加载和保存配置,使得下次运行程序时可以快速恢复之前的设置。这是一个实用的小工具,可以帮助我们更高效地管理文件复制任务。希望你能从中学到一些有用的技巧,并应用到自己的项目中。
以上就是使用Python和XML实现文件复制工具的完整代码的详细内容,更多关于Python XML文件复制工具的资料请关注脚本之家其它相关文章!
相关文章
Python3 requests文件下载 期间显示文件信息和下载进度代码实例
这篇文章主要介绍了Python3 requests文件下载 期间显示文件信息和下载进度代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-08-08
最新评论