通过根据一组字符将文件拆分为列表项,将文本文件读入python

时间:2014-03-25 15:17:56

标签: python list readfile splice dna-sequence

我有一个包含以下内容的纯文本文件:

@M00964: XXXXX
YYY
+
ZZZZ 
@M00964: XXXXX
YYY
+
ZZZZ
@M00964: XXXXX
YYY
+
ZZZZ

我希望将其读入根据ID代码@M00964分成项目的列表中,即:

['@M00964: XXXXX
YYY
+
ZZZZ' 
'@M00964: XXXXX
YYY
+
ZZZZ'
'@M00964: XXXXX
YYY
+
ZZZZ']

我尝试过使用

in_file = open(fileName,"r")
sequences = in_file.read().split('@M00964')[1:]
in_file.close()

但这会删除ID序列@M00964。有没有办法保持这个ID序列?

另外一个问题是如何在列表中维护空格(而不是/ n符号)。

我的总体目标是读取这组项目,例如,取第一项,然后将它们写回文本文件,保留所有原始格式。

3 个答案:

答案 0 :(得分:3)

如果您的文件很大并且您不想将整个内容保存在内存中,则可以使用此辅助函数迭代单个记录:

def chunk_records(filepath)
    with open(filepath, 'r') as f:
        record = []
        for line in f:
            # could use regex for more complicated matching
            if line.startswith('@M00964') and record:
                yield ''.join(record)
                record = []
            else:
                record.append(line)
        if record:
            yield ''.join(record)

一样使用它
for record in chunk_records('/your/filename.txt'):
    ...

或者如果你想要整个记忆中的东西:

records = list(chunk_records('/your/filename.txt'))

答案 1 :(得分:0)

只需在@符号上拆分:

with open(fileName,"r") as in_file:
    sequences = in_file.read().replace("@","###@").split('###')

答案 2 :(得分:0)

具体到您的示例,您不能执行以下操作:

in_file = open(fileName, 'r')
file = in_file.readlines()

new_list = [''.join(file[i*4:(i+1)*4]) for i in range(int(len(file)/4))]
list_no_n = [item.replace('\n','') for item in new_list]

print new_list
print list_no_n

[扩展表格]

new_list = []
for i in range(int(len(file)/4)): #Iterates through 1/4 of the length of the file lines.
                                  #This is because we will be dealing in groups of 4 lines
    new_list.append(''.join(file[i*4:(i+1)*4])) #Joins four lines together into a string and adds it to the new_list

[写入新文件]

write_list = ''.join(new_list).split('\n')
output_file = open(filename, 'w')
output_file.writelines(write_list)