I have created a tkinter GUI that allows to analyse a selected Word document. The user can select a file to analyse by pressing the upload button.
Before starting the analysis, I would like to backup the selected document. To accomplish this I tried implementing a function (executed by pressing the upload button as well) which uses the asksaveasfile feature of tkinter. This somewhat works as it pops ups as save as file dialogue after the user has selected a file using a diaogue box generated using askopenfile.
However, I have not been able to pass the the name of the selected file to this function (file_save_as()) so I can backup that file. I would like to know how I can save a copy of the selected document under a new file name (by adding '_backup' to the original name), without having to manually type this. For example if the selected document is titled, 'myfile.docx', then the backup should be called, 'myfile_backup.docx'. This file renaming should be done automatically
Any form of help would be appreciated. If there are any questions regarding the code, please ask.
The code for the upload button is shown here:
# upload button settings
upload_btn = tk.Button(root, command=lambda: [file_open(), file_save_as()])
upload_btn.configure(background="blue", font="{Arial} 16", text="Upload")
upload_btn.place(anchor="nw", relheight="0.10", relwidth="0.15", relx="0.10", rely="0.10", x="0", y="0")
The code for the function to open a file is shown here (FYI, the returned variable 'filename' contains the file path of the selected document):
# function to open a Word document using file explorer
def file_open():
upload_btn.configure(text="waiting...")
file = askopenfile(parent=root, mode='r', title="Choose a file", filetypes=[(".docx file", "*.docx")])
upload_btn.configure(text="Upload")
global filename
filename = file.name
file_label.configure(text="Chosen File: " filename)
return filename
The code for the function to backup the file is shown here:
def file_save_as():
copy_file = asksaveasfile(parent=root, mode='r', title="Backup chosen file", filetypes=[("Word file", "*.docx")])
CodePudding user response:
If you want to save the copy of the original file to selected folder, it is better to use askdirectory()
instead of asksaveasfile()
, then construct the output filename programmatically and use shutil.copy2()
to backup the original file:
...
from tkinter.filedialog import askdirectory
import pathlib
import shutil
...
def file_save_as():
folder = askdirectory(title="Choose backup folder")
if folder:
# filename is the selected file in file_open()
src = pathlib.Path(filename)
# src.stem is the filename without the directories and file extension parts
# src.suffix is the file extension, i.e. ".docx"
dst = pathlib.Path(folder) / f'{src.stem}_backup{src.suffix}'
# copy the source file to destination file using shutil.copy2()
shutil.copy2(src, dst)
...