python 提取文件指定列的方法示例

yipeiwu_com6年前Python基础

之前用featureCount 处理得到结果,要提出第一列gene_id 和 readcount 列,首先软件输出的第一行默认是你使用的命令行,没有用,用bash批量删掉。

for i in `ls`;do sed -i '1d' $i;done

删除当前文件夹下所有文件第一行。

其实提出两列很简单,不过我受够了每次一个文件执行一次的烦。想搞成别的程序调用时命令行参数直接就行。第一次知道sys.argv这玩意,学到了。

我设置了 -i 输入,-o 输出 这两个参数来判断输入输出文件个数,不过对于错误命令行输入的判断还很欠缺,毕竟只有自己用。

上代码:

import sys
leng=len(sys.argv)
for i in range(leng): # index the input file and output file location,maybe it's too complex
 if sys.argv[i]=="-i":
 it=i
 if sys.argv[i]=="-o":
 out=i
for i in range(it+1,out): # input file number(there should have same # of in and out file)
 print(sys.argv[i])
 file=open(sys.argv[i],'r')
 f=open(sys.argv[i+out-it],'w')
 count=[]
 for lines in file.readlines():
 two=[]
 lines=lines.rstrip('\n')
 b=lines.split('\t')
 two.append(b[0])
 if(b[6].startswith('.')): #chage path to count,some output problem
  b[6]="count"
 two.append(b[6])
 s='\t'.join(two)
 f.write(s+'\n')
 f.close

其实python里面 str 和list 弄的还是昏头昏脑的,每次都要错了再改。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...

Python2.x和3.x下maketrans与translate函数使用上的不同

maketrans和translate函数是进行字符串字符编码的常用方法。本文着重点在于演示其基本用法和在不同版本下操作的差异。本文提到的2.X版本指2.6以上的版本,3.X版本指3.1...

在Python中os.fork()产生子进程的例子

例1 import os print 'Process (%s) start...' %os.getpid() pid = os.fork() if pid==0: print...

python操作excel文件并输出txt文件的实例

如下所示: #coding=utf-8 import os import xlrd #excel文件放置在当前路径 path='model.xls' #打开文件 data=xlrd....

Python手机号码归属地查询代码

Python手机号码归属地查询代码

简单的一个例子,是以前用Dephi写的,前不久刚实现了一个在Python中使用Delphi控件来编写界面程序,于是趁热写一个类似的的查询方案。 本实例是通过www.ip138.com这...