在Python中从单个文件生成多个文件

0 投票
2 回答
1810 浏览
提问于 2025-04-15 13:43

我有一个文件,内容如下:

序列 A.1.1 细菌
ATGCGCGATATAGGCCT
ATTATGCGCGCGCGC

序列 A.1.2 病毒
ATATATGCGCCGCGCGTA
ATATATATGCGCGCCGGC

序列 B.1.21 黑猩猩
ATATAGCGCGCGCGCGAT
ATATATATGCGCG

序列 C.21.4 人类
ATATATATGCCGCGCG
ATATAATATC

我想从这个文件中,把 A、B 和 C 类别的序列分开,做成三个不同的文件。请推荐一些资料,帮我理解如何实现这个功能。谢谢!最终的输出应该是三个文件,一个是 'A' 类的,第二个是 'B' 类的,第三个是 'C' 类的序列。

2 个回答

0

我不太确定你想要的输出是什么样的,但听起来你需要类似这样的东西:

#!/usr/bin/python

# Open the input file
fhIn = open("input_file.txt", "r")

# Open the output files and store their handles in a dictionary
fhOut = {}
fhOut['A'] = open("sequence_a.txt", "w")
fhOut['B'] = open("sequence_b.txt", "w")
fhOut['C'] = open("sequence_c.txt", "w")

# Create a regexp to find the line naming the sequence
Matcher = re.compile(r'^Sequence (?P<sequence>[A-C])')

# Iterate through each line in the file
CurrentSequence = None
for line in fhIn:
    # If the line is a sequence identifier...
    m = Matcher.match(line)
    if m is not None:
        # Select the appropriate sequence from the regexp match
        CurrentSequence = m.group('sequence')
    # Uncomment the following two lines to skip blank lines
    # elif len(line.strip()) == 0:
    #     pass
    # Print out the line to the current sequence output file
    # (change to else if you don't want to print the sequence titles)
    if CurrentSequence is not None:
        fhOut[CurrentSequence].write(line)

# Close all the file handles
fhIn.close()
fhOut['A'].close()
fhOut['B'].close()
fhOut['C'].close()

不过这个代码完全没有测试过哦...

2

你想要做的事情不是特别清楚,但大概可以这样理解:

currout = None
seqname2file = dict()

for line in open('thefilewhosenameyoudonottellus.txt'):
  if line.startswith('Sequence '):    
    seqname = line[9]  # A or B or C
    if seqname not in seqname2file:
      filename = 'outputfileforsequence_%s.txt' % seqname
      seqname2file[seqname] = open(filename, 'w')
    currout = seqname2file[seqname]
  currout.write(line)

for f in seqname2file.values():
  f.close()

这段代码应该能让你接近目标。如果你想要三个独立的文件(分别对应A、B和C),这些文件里包含了输入文件中的所有行,那基本上就快完成了。不过,你可能需要给这些文件起个更好的名字(但你没有告诉我们这些名字是什么;-),除此之外,做一些小调整就可以了。

顺便说一下,如果你能提供一些你希望得到的输出结果的例子,这样会大大帮助我们更有效地帮助你,而不是在黑暗中摸索和猜测!-)

撰写回答