【问题标题】:Why wont my code write to the file output? local variable referenced before assignment为什么我的代码不会写入文件输出?赋值前引用的局部变量
【发布时间】:2021-03-11 15:13:41
【问题描述】:

我编写了一些代码来读取我的文本文件,找到一组与基因相关的数字,然后使用这些数字来搜索基因本身,这样我就可以提取出一堆包含每个基因的文本文件。 我已经成功地得到了数字,但是我在文件写入方面遇到了问题。我收到错误“分配前引用的局部变量 'gene_substring'”。我做了一些研究并尝试使用 global 来修复它,但它在其他地方抛出了错误。

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

我该如何解决这个问题?谢谢:)

【问题讨论】:

  • gene_substring 仅被定义为if start > stop:,错误发生是因为事实并非如此。您确定要开始 > 停止吗?
  • 要么你打错了>而不是
  • @ThierryLathuille 我并不迫切需要 if 语句,所以我把它拿出来了!感谢您的帮助:)

标签: python file global-variables local-variables


【解决方案1】:

变量gene_substring仅在条件start > stop为真时初始化。但是如果不满足要求怎么办?你必须初始化变量gene_substring,或者干脆移动它

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

进入声明if start > stop:

另外,请确保 if 语句是正确的

【讨论】:

  • 谢谢,这有帮助。我并不迫切需要 if 语句,所以我把它拿出来了!
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 2011-11-06
  • 2018-01-12
  • 1970-01-01
相关资源
最近更新 更多