备份文件小程序(Python)

温馨提示:如果对你们有帮助的话,那就点个免费的赞吧 (๑>؂<๑)!!!

                  有特别需求也可以关注后评论区留言(๑>؂<๑)!!!

题目要求:

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()

运行结果:

 

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: Python编写程序可以实现文件备份功能,具体步骤如下: 1. 导入模块 ``` import shutil ``` 2. 定义备份函数 ``` def backup_file(src_file, dst_dir): shutil.copy(src_file, dst_dir) ``` 3. 调用备份函数 ``` backup_file('file.txt', 'backup/') ``` 其,`src_file`为要备份文件路径,`dst_dir`为备份文件存放的目录路径。以上代码会将`file.txt`文件备份到`backup/`目录下。 希望能对您有所帮助。 ### 回答2: Python是一种高级编程语言,可以用来开发各种应用程序,包括文件备份功能。下面是使用Python编写程序实现文件备份功能的步骤: 第一步:导入需要的库文件Python代码的开头,需要导入所需的库文件。在这种情况下,我们需要使用os和shutil库。 import os import shutil 第二步:定义备份的源和目标路径 在程序定义备份的源和目标路径。例如,假设要备份的源文件位于“/Users/myuser/Documents/”目录下,同时备份到“/Users/myuser/backup/”目录下。 src_dir = "/Users/myuser/Documents/" dst_dir = "/Users/myuser/backup/" 第三步:判断备份目录是否存在 如果备份目录不存在,则需要创建它。可以使用os模块的makedirs函数。如果备份目录已经存在,则跳过这一步。 if not os.path.exists(dst_dir): os.makedirs(dst_dir) 第四步:备份文件 使用shutil模块的copy2函数备份源目录的所有文件目标目录。该函数将源文件的元数据,如时间戳和权限等一起复制到目标文件。如果要备份整个目录结构,可以使用shutil模块的copytree函数。 file_list = os.listdir(src_dir) for file in file_list: src_path = os.path.join(src_dir, file) dst_path = os.path.join(dst_dir, file) shutil.copy2(src_path, dst_path) 运行完整的程序后,源目录的所有文件都将被复制到目标目录。如果要每天自动备份文件,可以将该程序加入到计划任务或使用Python第三方库schedule来定时运行该程序。 总结 这是使用Python编写程序实现文件备份功能的基本步骤。如此,即可创建一个可靠的文件备份程序,确保在需要时能够恢复数据。此外,Python编程也可以实现其他功能,如从本地磁盘文件读取数据、向目标服务器的数据库添加数据等等。Python编程也可以用于科学计算、机器学习、自然语言处理等领域。 ### 回答3: Python是一种非常强大的编程语言,可以用它编写程序来实现各种各样的功能,包括文件备份功能。 要实现文件备份的功能,我们可以使用Python的一些内置模块,比如`os`和`shutil`模块。这两个模块提供了许多用于文件和目录操作的函数和方法。 首先,我们需要用`os`模块来获取待备份文件的路径和文件名。这可以通过使用`os.path`模块的`join`方法来完成。例如: ```python import os # 获取待备份文件的路径和文件名 file_path = os.path.join('/path/to/file', 'filename.txt') ``` 接下来,我们需要将文件备份到一个新路径下,以避免覆盖原文件。我们可以使用`shutil`模块的`copy2`方法来完成文件备份。例如: ```python import shutil # 备份文件到新的路径 backup_path = os.path.join('/path/to/backup', 'filename_backup.txt') shutil.copy2(file_path, backup_path) ``` `copy2`方法不仅可以将文件复制到新的路径下,还可以将原文件的元数据(如创建时间、修改时间等)一并复制过来。 最后,我们可以通过一些简单的提示信息来告诉用户备份操作已经完成。例如: ```python print('文件备份成功!') ``` 在实际应用,我们还可以编写一些额外的功能,比如定时备份、自动压缩备份文件等,以满足不同用户的需求。 总之,Python是一种十分强大的编程语言,对于文件备份这样的任务,使用Python编写程序可以非常方便、高效地完成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳阳大魔王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值