使用Python和XML實現(xiàn)文件復(fù)制工具的完整代碼
引言
在本篇博客中,我們將學(xué)習(xí)如何使用 wxPython 構(gòu)建一個簡單的文件復(fù)制工具,并將文件路徑和目標(biāo)目錄的配置信息保存到 XML 文件中。通過這種方式,我們可以在下次運(yùn)行程序時輕松加載之前保存的配置。
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. 運(yùn)行程序
最后,運(yùn)行程序:
if __name__ == '__main__':
app = wx.App()
FileCopyApp(None, title='File Copier')
app.MainLoop()
結(jié)果如下


總結(jié)
通過這篇博客,我們學(xué)習(xí)了如何使用 wxPython 構(gòu)建一個簡單的文件復(fù)制工具,并將文件路徑和目標(biāo)目錄的配置信息保存到 XML 文件中。我們可以輕松加載和保存配置,使得下次運(yùn)行程序時可以快速恢復(fù)之前的設(shè)置。這是一個實用的小工具,可以幫助我們更高效地管理文件復(fù)制任務(wù)。希望你能從中學(xué)到一些有用的技巧,并應(yīng)用到自己的項目中。
以上就是使用Python和XML實現(xiàn)文件復(fù)制工具的完整代碼的詳細(xì)內(nèi)容,更多關(guān)于Python XML文件復(fù)制工具的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python光學(xué)仿真學(xué)習(xí)Gauss高斯光束在空間中的分布
這篇文章主要介紹了Python光學(xué)仿真學(xué)習(xí)中Gauss高斯光束在空間中的分布理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-10-10
python elasticsearch環(huán)境搭建詳解
在本篇文章里小編給大家整理的是關(guān)于python elasticsearch環(huán)境搭建的相關(guān)知識點(diǎn)內(nèi)容,有需要的朋友們可以參考下。2019-09-09
Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)字典相關(guān)計算問題示例
這篇文章主要介紹了Python字典相關(guān)計算問題,結(jié)合實例形式總結(jié)分析了Python字典相關(guān)的最小值、最大值、排序等操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-02-02
python中使用paramiko模塊并實現(xiàn)遠(yuǎn)程連接服務(wù)器執(zhí)行上傳下載功能
paramiko是用python語言寫的一個模塊,遵循SSH2協(xié)議,支持以加密和認(rèn)證的方式,進(jìn)行遠(yuǎn)程服務(wù)器的連接。這篇文章主要介紹了python中使用paramiko模塊并實現(xiàn)遠(yuǎn)程連接服務(wù)器執(zhí)行上傳下載功能,需要的朋友可以參考下2020-02-02
python+PyQt5高效實現(xiàn)Windows文件快速檢索工具
在Windows系統(tǒng)中,文件檢索一直是個痛點(diǎn),本文將介紹一個基于PyQt5的開源解決方案,實現(xiàn)類似Everything的高效文件檢索功能,有需要的可以了解下2025-09-09
深入理解Python虛擬機(jī)中元組(tuple)的實現(xiàn)原理及源碼
在本篇文章當(dāng)中主要給大家介紹?cpython?虛擬機(jī)當(dāng)中針對列表的實現(xiàn),在?Python?中,tuple?是一種非常常用的數(shù)據(jù)類型,在本篇文章當(dāng)中將深入去分析這一點(diǎn)是如何實現(xiàn)的2023-03-03

