我有一个标签分隔文件,如下所示:
chrom start stop strand isoform mu_codon mut_codon2 more_info
chr22 43089055 43089055 - NM_017436 C 903delC
chr22 43089715 43089717 - NM_017436 CTT 241_243delTTC
chr22 43089657 43089657 - NM_017436 G 301delG
chr12 53701873 53701875 - NM_015665 TTC A 1292_1294delTTCinsA
我编写了一个脚本来计算mut_codon2列中的字符数,并将信息写入文件。
这是我的剧本:
import csv
OutputFileName = "indels_mut_count2.txt"
OutputFile = open(OutputFileName, 'w')
with open("indels_mut_removed.txt") as f:
for line in f:
columns = line.split('\t')
chrom = columns[0]
start = columns[1]
stop = columns[2]
strand = columns[3]
isoform = columns[4]
codon1 = columns[5]
codon2 = columns[6]
info = columns[7]
length = len(codon1)
length2 = len(codon2)
OutputFile.write(''+chrom+'\t'+str(start)+'\t'+str(stop)+'\t'+strand+'\t'+isoform+'\t'+codon1+'\t'+codon2+'\t'+str(length)+'\t'+str(length2)+'\t'+info+'\n')
我几乎肯定我的问题与OutputFile.write()
有关,因为输出的文件在我要输出的每一行之后添加了空行。这是一个例子:
chrom start stop strand isoform mu_codon mut_codon2 8 10 more_info
chr22 43089055 43089055 - NM_017436 C 1 1 903delC
chr22 43089715 43089717 - NM_017436 CTT 3 1 241_243delTTC
chr22 43089657 43089657 - NM_017436 G 1 1 301delG
但是,我也收到的错误是:
info = columns[7]
IndexError: list index out of range
我不确定我做错了什么。有什么建议吗?
答案 0 :(得分:3)
我建议您使用csv.csvreader
而不是手动分割线条。拆分不会处理转义和其他一些事情,因此csv.csvreader
更加安全。
有关信息,您遇到此问题是因为您没有使用\n
删除每行末尾的rstrip()
。然后您将其写入输出,并在调用\n
时添加(第二个)write()
。
但请再次使用csv.csvreader
。
答案 1 :(得分:2)
csv
(如Arkanosis所示)是一个不错的选择;否则:
with open("indels_mut_removed.txt") as f:
for line in f:
line = line.strip() # removes trainling '\n'
columns = line.split('\t')
答案 2 :(得分:1)
要使用csv,您可能会执行与此类似的操作:
</p>
鉴于此输入:
import csv
with open(fn) as fin, open(fo, 'w') as fout:
reader=csv.reader(fin, delimiter='\t')
writer=csv.writer(fout, delimiter='\t')
headers_in=next(reader)
headers_out=headers_in[:-1]+['len codon 1', 'len codon 2']+headers_in[-1:]
writer.writerow(headers_out)
for row_in in reader:
row_out=row_in[:-1]+map(len, [row_in[5], row_in[6]])+row_in[-1:]
writer.writerow(row_out)
生成此输出:
chrom start stop strand isoform mu_codon mut_codon2 more_info
chr22 43089055 43089055 - NM_017436 C 903delC
chr22 43089715 43089717 - NM_017436 CTT 241_243delTTC
chr22 43089657 43089657 - NM_017436 G 301delG
chr12 53701873 53701875 - NM_015665 TTC A 1292_1294delTTCinsA