我正在编写一个代码,它将过滤 csv 文件中的值并将相关行写入一个文件,将接受但不需要的行写入另一个文件,并将错误文件写入第三个文件。
这是我写的:
#variables
doc = '/lab01/Projects/Lords_Projects/mna_exons.csv'
save = '/lab01/Projects/Lords_Projects/mna_exac.csv'
other = '/lab01/Projects/Lords_Projects/mna_alt.csv'
error = '/lab01/Projects/Lords_Projects/mna_error.csv'
seek = 'ExAC_ALL'
comp = .05
#script
import csv
#open
read = open(doc, 'rb')
write = open(save, 'wb')
dif = open(other, 'wb')
mis = open(error, 'wb')
#text conversion
reader = csv.DictReader(read, delimiter=',')
copy = csv.DictWriter(write, delimiter='\t', fieldnames=reader.fieldnames)
alt = csv.DictWriter(dif, delimiter='\t', fieldnames=reader.fieldnames)
er = csv.DictWriter(mis, delimiter='\t', fieldnames=reader.fieldnames)
#headers
head = {}
for n in reader.fieldnames:
head[n] = n
copy.writerow(head)
alt.writerow(head)
er.writerow(head)
#sorting
for row in reader:
try:
if float(row[seek]) < comp and float(row[seek]) > -comp:
copy.writerow(row)
elif float(row[seek]) >= comp or float(row[seek]) <= -comp:
alt.writerow(row)
except:
try:
if row[seek] == 'N/A':
copy.writerow(row)
except:
prob = csv.writer(write, delimiter='\t')
er.writerow(row)
prob.writerow("Value Not Float\n")
#Close
read.close()
write.close()
dif.close()
mis.close()
#Error Check
if 'Value Not Float\n' in open(save, 'r').read():
print('Error')
open(save, 'r').close()
当我运行它时,它给了我这个错误信息:
回溯(最后一次调用):文件“csv_cond_filter.py”,第 45 行,在 er.writerow(row) 文件“/usr/lib64/python2.7/csv.py”,第 152 行,在 writerow 返回 self.writer .writerow(self._dict_to_list(rowdict)) 文件“/usr/lib64/python2.7/csv.py”,第 148 行,在 _dict_to_list + 中,“.join([repr(x) for x in wrong_fields])) ValueError:字典包含不在字段名中的字段:无
为了测试具体可能是什么错误,我将错误行作为注释并再次运行脚本。它没有给我一条错误消息,也没有打印我指定它写的错误值,如果它无法对段进行分类,所以我怀疑这是一个语法错误,但我是 python 新手,我不知道对 csv 模块或 DictWriter 了解不够。