错误:未定义变量名称

时间:2015-09-05 11:49:09

标签: python python-2.7 csv file-io

我编写了以下代码,但是我收到一条错误消息:名称'acc'未定义。我该如何解决?

 import csv

    with open(r"C:\Users\garfield\Python27\trial.txt") as file,     open(r"C:\Users\garfield\Python27\outp.csv", "a+") as f:
 x=file.read()
 m=x.split()
 writer = csv.writer(f, delimiter =",",quoting=csv.QUOTE_MINIMAL)
 for i in range(len(m)-1):
    if "ACCESSION" in m[i]:
        acc=m[i+1]
    if '/host' in m[i]:
        host1=m[i].split('/host')[1].split('\n')[0]
        host2=m[i+1]
        host=host1+" "+host2 
    if "5'UTR" in m[i]:
        utr=m[i+1]
    data=[acc,host,utr]
    writer.writerow(data)

1 个答案:

答案 0 :(得分:0)

从您的代码看来,您正在尝试解析整个文件,从中创建acc / utr / host变量,然后将其写入csv,对我来说它看起来像你要写的是csv中的一行,在完成输入文件之后,如果是这样,行的缩进 -

data=[acc,host,utr]
writer.writerow(data)

错误,它应该在for循环之外缩进,而不是在其中示例 -

for i in range(len(m)-1):
    if "ACCESSION" in m[i]:
        acc=m[i+1]
    if '/host' in m[i]:
        host1=m[i].split('/host')[1].split('\n')[0]
        host2=m[i+1]
        host=host1+" "+host2 
    if "5'UTR" in m[i]:
        utr=m[i+1]
writer.writerow([acc,host,utr])            #there is no need for an extra variable here.

此外,您应该为所有三个变量设置一些默认值,以处理在文件中找不到特定行的情况。