UnboundLocalError: local variable 'dest_file_name' referenced before assignment

Question:

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())
Asked By: Arthetine

||

Answers:

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))
Answered By: mipadi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.