温馨提示:如果对你们有帮助的话,那就点个免费的赞吧 (๑><๑)!!!
有特别需求也可以关注后评论区留言(๑><๑)!!!
题目要求:
1.编写函数1,对文件进行备份,读取要备份文件中的内容写入目标目录中新创建的同名文件中,形参为目标目录和源文件。
2.编写函数2,实现用户输入备份的目标目录和要备份的源文件,并判断输入源文件是否为文件,如果是执行备份操作,不是提示重新输入。
3.调用函数2,实现文件备份。
实现代码:
import os
import shutil
def backup_file(target_dir, source_file):
if not os.path.exists(source_file) or not os.path.isfile(source_file):
print(f"源文件 {source_file} 不存在或不是一个文件。")
return
try:
os.makedirs(target_dir, exist_ok=True)
except OSError as e:
print(f"在尝试创建 {target_dir} 时发生错误: {e}")
return
target_file = os.path.join(target_dir, os.path.basename(source_file))
try:
shutil.copy2(source_file, target_file)
print(f"文件 {source_file} 已备份到 {target_file}")
except Exception as e:
print(f"备份文件时出错: {e}")
def backup_with_user_input():
while True:
target_dir = input("请输入备份的目标目录(确保该目录存在且可写): ")
source_file = input("请输入要备份的源文件路径(确保该文件存在): ")
if os.path.isfile(source_file) and os.access(target_dir, os.W_OK):
backup_file(target_dir, source_file)
break
elif not os.path.isfile(source_file):
print("输入的不是文件,请重新输入!")
elif not os.access(target_dir, os.W_OK):
print("目标目录不可写,请重新输入!")
backup_with_user_input()
运行结果:
代码升级:
增加GUI(图形交互界面),更简洁的操作,更加优质的用户体验,提醒错误出现在哪里。
以下程序有FileBackup备份类,FileBackupWindow图形搭建类。
import os
import shutil
import tkinter.messagebox
from tkinter import*
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
class FileBackup:
def __init__(self, window):
self.window = window
def backup_file(self, target_dir, source_file):
if not os.path.exists(source_file) or not os.path.isfile(source_file):
tkinter.messagebox.showerror("错误", f"源文件 {source_file} 不存在或不是一个文件。")
return
try:
os.makedirs(target_dir, exist_ok=True)
except OSError as e:
tkinter.messagebox.showerror("错误", f"在尝试创建 {target_dir} 时发生错误: {e}")
return
target_file = os.path.join(target_dir, os.path.basename(source_file))
try:
shutil.copy2(source_file, target_file)
except Exception as e:
tkinter.messagebox.showerror("错误", f"备份文件时出错: {e}")
class FileBackupWindow:
def __init__(self):
self.window = Tk()
self.window.title("文件备份器")
self.file_path = StringVar()
self.selected_file = None
self.target_dir = StringVar()
self.menubar = Menu(self.window)
self.filemenu = Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="打开文件", command=self.open_file)
self.filemenu.add_command(label="备份文件", command=self.backup_selected_file)
self.filemenu.add_separator()
self.filemenu.add_command(label="退出", command=self.window.quit)
self.helpmenu = Menu(self.menubar, tearoff=0)
self.helpmenu.add_command(label="关于", command=self.show_about)
self.helpmore = Menu(self.menubar, tearoff=0)
self.helpmore.add_command(label="存储", command=self.showMore)
self.menubar.add_cascade(label="文件", menu=self.filemenu)
self.menubar.add_cascade(label="帮助", menu=self.helpmenu)
self.window.config(menu=self.menubar)
self.main_frame = Frame(self.window)
self.main_frame.pack(fill=BOTH, expand=True)
frame1 = Frame(self.window)
frame1.pack()
labelSoucePath = Label(frame1,text="源路径:")
labelSoucePath.grid(row=0, column=0)
self.soucePath = StringVar()
entrySoucePath = Entry(frame1,width=80,textvariable=self.file_path)
entrySoucePath.grid(row=0,column=1)
btnOpen = Button(frame1,text="打开",command=self.open_file)
btnOpen.grid(row=0, column=2)
frame2 = Frame(self.window)
frame2.pack()
labelBackupPath = Label(frame2,text="新路径:")
labelBackupPath.grid(row=1, column=0)
self.backupPath = StringVar()
entryBackupPath = Entry(frame2,width=80,textvariable=self.target_dir)
entryBackupPath.grid(row=1, column=1)
btnEncrypt = Button(frame2, text="打开", command=self.select_file)
btnEncrypt.grid(row=1, column=2)
self.text = Text(self.window)
self.text.pack(fill=BOTH, expand=True)
self.backup_button = Button(self.window, text="备份文件", command=self.backup_selected_file)
self.backup_button.pack(pady=10)
self.window.mainloop()
def open_file(self):
try:
inFileName = askopenfilename()
inFile = open(inFileName,"r",encoding="utf-8")
self.selected_file = inFileName
self.file_path.set(inFileName)
self.fileCont = inFile.read()
self.text.delete(1.0,END)
self.text.insert(END,self.fileCont)
inFile.close()
except:
tkinter.messagebox.showerror("报错","选择备份文件不成功,请重新选择!")
def select_file(self):
if not self.selected_file:
tkinter.messagebox.showerror("错误", "请先选择一个文件。")
return
target_dir = filedialog.askdirectory()
if not target_dir:
return
self.target_dir.set(target_dir)
def backup_selected_file(self):
if not self.file_path.get():
tkinter.messagebox.showerror("错误", "请先选择一个文件。")
return
if not self.target_dir.get():
tkinter.messagebox.showerror("错误", "请先选择一个备份路径。")
return
FileBackup(self.window).backup_file(self.target_dir.get(), self.file_path.get())
def show_about(self):
tkinter.messagebox.showinfo("关于", "这是一个简单的文件备份器。")
def showMore(self):
tkinter.messagebox.showinfo("关于", "本功能暂时并未开放,您的需求是我最大的动力!")
if __name__ == "__main__":
FileBackupWindow()
运行结果: