从python

时间:2019-04-18 11:13:48

标签: python-3.x file-read

我有10000个文件,每个文件有2000个样本。每个文件都按照以下模式编写:

discoal 4 2000 55000 -Pt 1750.204699 17502.046985 -Pre 19252.251684 57756.755051
939889312 676473727

###Example 1
//
segsites: 3
positions: 0.000616 0.001428 0.001500
100
001
101
100

###Example 2
segsites: 6
positions: 0.001843 0.002019 0.002102 0.002431 0.003427 0.004103 
000101
101000
001100
110111

文件详细信息:

每个文件均以 discoal 和带有两个数字的行开头。这些行将被忽略。所需的数据是 segsites position 和我在 positions 之后的二进制值。每行(二进制值)将对应于矩阵中的一行。

隔离点的数量将对应于位置矢量的长度和二进制矩阵中的列数。例如,在第一个示例中,我的隔离站点为3,因此,我的位置向量中也将包含3个值。我的二进制矩阵的大小为4 x3。之所以为'4',是因为示例中有四行二进制值。

我的代码完成了所有这一切。但我只想保留那些隔离度小于5000的示例。

这只是一个例子。否则,我的隔离站点数最多为10000。我编写了遍历所有这些文件的代码。对于这些文件中的每一个,它都会获得#个隔离位点,位置,并将位置下方的二进制值放入矩阵中。例如,第一个示例的矩阵大小为4 x 3,第二个矩阵的大小为4 x 6。

我的代码是:

def reading_filenames(path_to_directory,extension,tot_segsites,positions,snp_matrix):
    """
    This function returns the file names in the directory of interest
    """

    path = path_to_directory + extension 
    files = glob.glob(path)

    i=0
    for file in files:     
        f=open(file, 'r')  
        #print('file : ',file)
        reading_file(f.readlines(),tot_segsites,positions,snp_matrix,i)
        i += 1

        f.close() 

    return files, snp_matrix

    #return [f for f in os.listdir(path_to_directory) if f.endswith(extension)]

def reading_file(file,tot_segsites,positions,snp_matrix,i):

    flag = False
    length = 0
    counter = 0
    array = np.zeros((chrm_num,6000))
    for line in file:
        if 'segsites:' in line:
            lst = (line.strip('\n').split(': '))
            res = int(lst[1])
            tot_segsites.append(res)

        elif 'position' in line:
            lst = line.strip('\n').split(': ')
            lst = lst[1:]
            res = [float(k) for k in lst[0].split(' ')]

            for j in range(len(res)):
                positions[i][j] = res[j]

            flag = True

        elif flag:
            lst = line.strip('\n')
            reading_snp_matrix(lst,length,chrm_num,counter,array)
            counter += 1
            flag = True

    snp_matrix.append((array))
    return snp_matrix

def reading_snp_matrix(line,length,chrm_num,counter,array):
    chromosome = list(map(int, line))
    for i in range(len(chromosome)):
        array[counter][i] = chromosome[i]

reading_filenames 函数仅读取文件夹中的文件,并为每个文件调用函数 reading_file 。然后, reading_file 函数读取节段,位置和二进制矩阵。但是,我想更改此代码,以便仅存储那些隔离点为5000或更少但不大于5000的隔离点,位置和二进制矩阵。我不知道如何用我编写的代码实现这一目标。 另外,您能告诉我一种有效的方式来读取我提到的格式的文件吗?因为这段代码很慢。

1 个答案:

答案 0 :(得分:0)

您可以读取文件,将其转换为csv,然后再次写入(一次)。然后,您可以使用pandas来读取csv并轻松对其进行操作