我有代码可以让我执行相当复杂的任务(至少对我来说):
import csv
import os.path
#open files + readlines
with open("C:/Users/Ivan Wong/Desktop/Placement/Lists of targets/Mouse/UCSC to Ensembl.csv", "r") as f:
reader = csv.reader(f, delimiter = ',')
#find files with the name in 1st row
for row in reader:
graph_filename = os.path.join("C:/Python27/Scripts/My scripts/Top targets",row[0]+"_nt_counts.txt.png")
if os.path.exists(graph_filename):
y = row[0]+'_nt_counts.txt'
r = open('C:/Users/Ivan Wong/Desktop/Placement/fp_mesc_nochx/'+y, 'r')
k = r.readlines()
r.close
del k[:1]
k = map(lambda s: s.strip(), k)
interger = map(int, k)
import itertools
#adding the numbers for every 3 rows
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.izip_longest(*args, fillvalue=fillvalue)
result = map(sum, grouper(3, interger, 0))
e = row[0]
print e
cDNA = open('C:/Users/Ivan Wong/Desktop/Placement/Downloaded seq/Mouse/MOUSE_mRNAs.txt', 'r')
seq = cDNA.readlines()
# get all lines that have a gene name
lineNum = 0;
lineGenes = []
for line in seq:
lineNum = lineNum +1
if '>' in line:
lineGenes.append(str(lineNum))
if '>'+e in line:
lineBegin = lineNum
cDNA.close
# which gene is this
index1 = lineGenes.index(str(lineBegin))
lineEnd = lineGenes[index1+1]
# linebegin and lineEnd now give you, where to look for your sequence, all that
# you have to do is to read the lines between lineBegin and lineEnd in the file
# and make it into a single string.
lineEnd = lineGenes[index1+1]
Lastline = int(lineEnd) -1
# in your code you have already made a list with all the lines (q), first delete
# \n and other symbols, then combine all lines into a big string of nucleotides (like this)
qq = seq[lineBegin:Lastline]
qq = map(lambda s: s.strip(), qq)
string = ''
for i in range(len(qq)):
string = string + qq[i]
# now you want to get a list of triplets, again you can use the for loop:
# first get the length of the string
lenString = len(string);
# this is your list codons
listCodon = []
for i in range(0,lenString/3):
listCodon.append(string[0+i*3:3+i*3])
proper_result = '\n'.join('%s, %s' % (nr, codon) for nr, codon in zip(result, listCodon))
with open(e+'.csv','wb') as outfile:
outfile.writelines(proper_result)
这些代码从 .csv 读取文件,从具有相同名称的文件的文件夹中识别,如果它们存在,那么它会继续处理一些数据并将它们写入 .csv,我的输出文件现在看起来像这样
它看起来完全没问题,但是有一个问题,我从我的数据中知道(我以不同的方式检查它)第二列应该比我得到的要长。我认为这是因为当结果(数字)和 listCodon(字母)都存在时,代码正在写入文件,因此我遗漏了一些东西。我该如何解决?
我尝试在写入文件之前打印 listCodon,发现所有三元组仍然存在,所以我猜问题出在此处:
proper_result = '\n'.join('%s, %s' % (nr, codon) for nr, codon in zip(result, listCodon))