Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UnboundLocalError: local variable 'dest_file_name' referenced before assignment

Having issue with the code, I’m getting error with this code, was trying to make script to take a backup of a file scheduled

from datetime import date
import os
import shutil
import schedule

today = date.today()
date_format = today.strftime("%d_%b_%Y_")

src_file_name = "file.txt"
src_folder = "C:\\Users\\Xealtron\\Desktop\\Backup\\BackupFolder"
dest_file_name = "file.txt"
dest_folder = "C:\\Users\\Xealtron\\Desktop\\bup"


def take_backup():
    try:

    if dest_file_name != "":
        dest_file_name = src_file_name
        shutil.copy2(os.path.join(src_folder, src_file_name),
                     os.path.join(dest_folder, date_format + dest_file_name))

except FileNotFoundError:
    print("File does not exists,\
    please give the complete path")


schedule.every(10).second.do(take_backup())

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dest_file_name is a global variable, as it is defined at the top-level of a script. When you assign a new value to a global variable within a function, you have to declare that variable to be global:

def take_backup():
    global dest_file_name  # Declare the variable to be global
    if dest_file_name != "":
        dest_file_name = src_file_name
        shutil.copy2(os.path.join(src_folder, src_file_name),
                     os.path.join(dest_folder, date_format + dest_file_name))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading