Skip to content
Advertisement

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

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement