Python 将数据子集并计算每个文件中的行数

Python 将数据子集并计算每个文件中的行数,python,function,Python,Function,我试图将数据从一个文件子集到两个单独的文件,并分别计算每个文件中的行数 ID,MARK1,MARK2 sire1,AA,BB dam2,AB,AA sire3,AB,- dam1,AA,BB IND4,BB,AB IND5,BB,AA 其中一个文件是: ID,MARK1,MARK2 sire1,AA,BB dam2,AB,AA sire3,AB,- dam1,AA,BB ID,MARK1,MARK2 IND4,BB,AB IND5,BB,AA 另一个是: ID,MARK1,MARK2

我试图将数据从一个文件子集到两个单独的文件,并分别计算每个文件中的行数

   ID,MARK1,MARK2
sire1,AA,BB
dam2,AB,AA
sire3,AB,-
dam1,AA,BB
IND4,BB,AB
IND5,BB,AA
其中一个文件是:

ID,MARK1,MARK2
sire1,AA,BB
dam2,AB,AA
sire3,AB,-
dam1,AA,BB
ID,MARK1,MARK2
IND4,BB,AB
IND5,BB,AA
另一个是:

ID,MARK1,MARK2
sire1,AA,BB
dam2,AB,AA
sire3,AB,-
dam1,AA,BB
ID,MARK1,MARK2
IND4,BB,AB
IND5,BB,AA
这是我的密码:

import re
def file_len(filename):
    with open(filename, mode = 'r', buffering = 1) as f:
        for i, line in enumerate(f):
            pass
    return i

inputfile = open("test.txt", 'r')
outputfile_f1 = open("f1.txt", 'w')
outputfile_f2 = open("f2.txt", 'w')

matchlines = inputfile.readlines()
outputfile_f1.write(matchlines[0]) #add the header to the "f1.txt"
for line in matchlines:       
    if re.match("sire*", line):
        outputfile_f1.write(line)
    elif re.match("dam*", line):
        outputfile_f1.write(line)
    else:
        outputfile_f2.write(line) 
print 'the number of individuals in f1 is:', file_len(outputfile_f1)
print 'the number of individuals in f2 is:', file_len(outputfile_f2)
inputfile.close()
outputfile_f1.close()
outputfile_f2.close()
代码可以很好地分离文件的子集,但我特别不喜欢我将头添加到新文件的方式,我想知道是否有更好的方法可以做到这一点?此外,该函数在计算行数时看起来很好,但当我运行它时,它给了我一个错误

"Traceback (most recent call last):
  File "./subset_individuals_based_on_ID.py", line 28, in <module>
    print 'the number of individuals in f1 is:', file_len(outputfile_f1)
  File "./subset_individuals_based_on_ID.py", line 7, in file_len
    with open(filename, mode = 'r', buffering = 1) as f:
TypeError: coercing to Unicode: need string or buffer, file found
 "
“回溯(最近一次呼叫最后一次):
文件“/subset\u personals\u based\u on\u ID.py”,第28行,在
打印“f1中的个人数量为:”,文件\u len(输出文件\u f1)
文件“/subset\u personals\u基于\u ID.py”,第7行,在文件\u len中
打开(文件名,模式='r',缓冲=1)为f:
TypeError:强制使用Unicode:需要字符串或缓冲区,找到文件
"
所以我在谷歌上搜索了这个网站,添加了
buffering=1
(它最初不在代码中),仍然没有解决这个问题


非常感谢您帮助改进代码并清除错误。

我可能误解了您的意思,但我相信您只是在尝试这样做:

>>> with open('test', 'r') as infile:
...   with open('test_out1', 'w') as out1, open('test_out2', 'w') as out2:
...     header, *lines = infile.readlines()
...     out1.write(header)
...     out2.write(header)
...     for line in lines:
...       if line.startswith('sir') or line.startswith('dam'):
...         out1.write(line)
...       else:
...         out2.write(line)
测试的内容
之前:

ID,MARK1,MARK2
sire1,AA,BB
dam2,AB,AA
sire3,AB,-
dam1,AA,BB
IND4,BB,AB
IND5,BB,AA
test\u out1
之后的内容:

ID,MARK1,MARK2
sire1,AA,BB
dam2,AB,AA
sire3,AB,-
dam1,AA,BB
ID,MARK1,MARK2
IND4,BB,AB
IND5,BB,AA
test_out2
之后的内容:

ID,MARK1,MARK2
sire1,AA,BB
dam2,AB,AA
sire3,AB,-
dam1,AA,BB
ID,MARK1,MARK2
IND4,BB,AB
IND5,BB,AA

您还可以使用
itertools.tee
将输入拆分为多个流,并分别进行处理

import itertools

def write_file(match, source, out_file):
    count = -1
    with open(out_file, 'w') as output:
        for line in source:
            if count < 0 or match(line):
                output.write(line)
                count += 1

    print('Wrote {0} lines to {1}'.format(count, out_file))


with open('test.txt', 'r') as f:
    first, second = itertools.tee(f.readlines())

    write_file(lambda x: not x.startswith('IND'), first, 'f1.txt')
    write_file(lambda x: x.startswith('IND'), second, 'f2.txt')
导入itertools
def写入文件(匹配、源、输出文件):
计数=-1
将打开的(out_文件,'w')作为输出:
对于行输入源:
如果计数小于0或匹配(行):
输出。写入(行)
计数+=1
打印('将{0}行写入{1}'。格式(计数,输出文件))
以open('test.txt','r')作为f:
第一个,第二个=itertools.tee(f.readlines())
写入_文件(lambda x:not x.startswith('IND'),首先是'f1.txt')
写入_文件(lambda x:x.startswith('IND'),第二个'f2.txt')

编辑-删除多余的elif

您能解释一下“header,*lines=infle.readlines()”这是什么意思吗?当您只关心前几个值时,这是一种解压列表的有用方法<代码>a,b,c,*d=[0,1,2,3,4,5]生成0,b1,c2和d[3,4,5]。为什么有两个不同的条件做完全相同的事情?只需使用
。那太尴尬了。谢谢