我想要做的是这样的脚本读取当前文件:
chr1,700244,714068,LOC100288069,982
chr1,1568158,1570027,MMP23A,784
chr1,1567559,1570030,MMP23A,784
chr1,1849028,1850740,TMEM52,799
chr1,2281852,2284100,LOC100129534,934
chr1,2281852,2284100,LOC100129534,800
chr1,2460183,2461684,HES5,819
chr1,2460183,2461684,HES5,850
chr1,2517898,2522908,FAM213B,834
chr1,2518188,2522908,FAM213B,834
chr1,2518188,2522908,FAM213B,834
chr1,2518188,2522908,FAM213B,834
chr1,2517898,2522908,FAM213B,834
如果第3列在行中重复,则将第4列的值相加并得到该总和的平均值。输出应为:
chr1,700244,714068,LOC100288069,982
chr1,1568158,1570027,MMP23A,784
chr1,1849028,1850740,TMEM52,799
chr1,2281852,2284100,LOC100129534,934
chr1,2460183,2461684,HES5,834.5
chr1,2517898,2522908,FAM213B,867
我尝试过这个脚本,但它没有用。谁能给我一些小费?
f1 = open('path', 'r')
reader1 = f1.read()
f3 = open('path/B_Media.txt','wb')
for line1 in f1:
coluna = line1.split(',')
chr = coluna[0]
start = coluna[1]
end = coluna[2]
gene = coluna[3]
valor_B = coluna[4]
previous_line = current_line
current_line = line
gene2 = previous_line[3]
soma_B2 = previous_line[4]
soma_de_B = int(valor_B)+int(soma_B2)
if gene == gene2:
x += 1
media_gene = soma_de_B/x
output = chr + "," + start + "," + end + "," + gene + "," +valor_B+","+media_gene
f3.write(output)
f3.flush()
print output
答案 0 :(得分:1)
当你需要知道接下来会发生什么时(以逐行阅读的方式说话),我会将阅读和写作分成两个不同的部分。
此外,csv
- 模块可能派上用场,因为您不必处理任何特殊情况(如文本中的逗号等),阅读/写作非常简单。使用with
打开文件通常是一种很好的做法,因为关闭它会自动处理。
现在有些代码: - )
from __future__ import division
import csv
gene = 3
valor_B = 4
data = []
with open('data.csv', 'r') as readfile:
reader = csv.reader(readfile)
for row in reader:
data.append(row)
values_to_add = []
with open('B_Media.txt','wb') as writefile:
writer = csv.writer(writefile)
for i in range(len(data)):
values_to_add.append(int(data[i][valor_B]))
# if last row or row is different from previous, write it
if i == len(data)-1 or data[i][gene] != data[i+1][gene]:
data[i][valor_B] = sum(values_to_add)/len(values_to_add)
writer.writerow(data[i])
values_to_add = []
基本上它首先从输入文件中读取所有内容并将其放入data
。然后,with
输出文件,它遍历每一行,执行以下操作:
sum()/len()
计算均值,并用新值替换相应的列,然后将其写入输出文件。结果:
chr1,700244,714068,LOC100288069,982.0
chr1,1567559,1570030,MMP23A,784.0
chr1,1849028,1850740,TMEM52,799.0
chr1,2281852,2284100,LOC100129534,867.0
chr1,2460183,2461684,HES5,834.5
chr1,2517898,2522908,FAM213B,834.0
(您可能会识别from __future__ import division
语句,这样可以确保在分割时我们可以使用非整数值,例如834.5
。