Search code examples
pythonfileglobal-variableslocal-variables

Why wont my code write to the file output? local variable referenced before assignment


I've written some code that reads through my text file, finds a set of numbers linked to gene, then uses those numbers to search for the gene itself so I can extract a bunch of text files containing each gene. I've successfully got the numbers out, but I'm having issues with the file writing. I get the error 'local variable 'gene_substring' referenced before assignment'. I've done some research and tried to use global to fix it, but it threw up errors elsewhere.

#function to extract the genes by using the numbers in my list
end_file = "/Users...."

def extract_genes(start_stop, genome_sequence):
    for start,stop in start_stop:
        # extracts start:stop gene from the sequence
            if start > stop:
                gene_substring = genome_sequence[0:start] + genome_sequence[stop:]

            # store in file
            with open(end_file + "/" + name + "+" + ".txt", "w",) as file:
                file.write(gene_substring)
#My code to get the output

work_dir = "/Users/"
for path in glob.glob(os.path.join(work_dir, "*.gbff")):
    numbers = extract_numbers(path)
    sequences = extract_seq(path)
    extract_genes(start_stop, sequences)
    print(path)

How can I fix this? Thanks :)


Solution

  • The variable gene_substring is only initialized when the condition start > stop is true. but what if the requirement is not satissfied? you must initialize the variable gene_substring, or simply move this

    with open(end_file + "/" + name + "+" + ".txt", "w",) as file:
                    file.write(gene_substring)
    

    into the statement if start > stop:

    Also, be sure the if statement is correct