Answers.Body: <p>A simple Biopython solution:</p>
  <pre class="lang-py prettyprint-override"><code>from Bio import SeqIO
  
  for record in SeqIO.parse(&quot;example.fa&quot;, &quot;fasta&quot;):
      SeqIO.write(record, record.id + &quot;.fa&quot;, &quot;fasta&quot;)
  </code></pre>
  <p>Note, if you have multiple sequences with the same id, only the last sequence will be kept in the final output files</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-05-15T03:06:14.473Z
Answers.Text: Thank you! It works excellent.
Answers.UserDisplayName: user8692
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-05-12T08:44:50.340Z
Answers.LastActivityDate: 2023-08-26T20:59:40.537Z
Answers.LastEditDate: 2023-08-26T20:59:40.537Z
Answers.UserDisplayName: Chris_Rands
Answers.Body: <p>There's an app for that! The <code>exonerate</code> package (see <a href="https://www.ebi.ac.uk/about/vertebrate-genomics/software/exonerate" rel="nofollow noreferrer">here</a>) includes a nice <code>fastaexplode</code> command that does exactly what you're looking for and will be much, much faster than anything we give you here since it is written in C and not a scripting language. Just install <code>exonerate</code> (you can do that with <code>sudo apt install exonerate</code> on Debian-based systems) and then:</p>
  <pre><code>fastaexplode file.fa
  </code></pre>
  <p>This will create these two files (<code>file.fa</code> is the original input file from your question):</p>
  <pre><code>$ ls
  file.fa  KQK14546.fa  KQK21959.fa
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-05-12T16:39:13.607Z
Answers.LastActivityDate: 2023-08-26T20:59:50.763Z
Answers.LastEditDate: 2023-08-26T20:59:50.763Z
Answers.UserDisplayName: terdon
Answers.Body: <p>That really depends on the tools you are using. If anything will do you can use the following python snippet.</p>
  <p>If you know that each sequence is on a single line and your file isnt gigantic use this</p>
  <h1>EDIT</h1>
  <p>Updated so the file isn't read to memory at once to address @terdon point. Although, the above solutions are probably much better.</p>
  <pre class="lang-py prettyprint-override"><code>with open( &quot;seqs.fasta&quot; ) as f:
      out = &quot;&quot;
      
      for line in f:
          if not line.strip(): continue 
          if line.startswith( &quot;&gt;&quot; ):
              if not type( out ) == str: out.close()
              gene = line[1:].strip().split()[0]
              out = open( f&quot;{gene}.fa&quot;, &quot;w&quot; )
              out.write( line )
              continue 
          out.write( line.strip() )
      
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-05-12T00:34:08.723Z
Answers.LastActivityDate: 2023-08-26T21:00:11.907Z
Answers.LastEditDate: 2023-08-26T21:00:11.907Z
Answers.UserDisplayName: sin tribu
Answers.Body: <p>This can also be done using awk. This is harder to read, but probably faster than python:</p>
  <pre class="lang-bash prettyprint-override"><code>awk 'sub(/^&gt;/,&quot;&quot;){
          FILE=<span class="math-container">$0".fa"; 
      print "&gt;"$</span>0 &gt;FILE; 
          next
      }{print &gt; FILE}' file.fa. 
  
  </code></pre>
  <p>This will define a new output file <code>FILE</code> at each header line, whose filename is the header minus the <code>&gt;</code> character, suffixed with <code>.fa</code>. And all lines in the file are appended to the current output file.</p>
  <p>EDIT: Changed to a faster version found on: <a href="https://crashcourse.housegordon.org/split-fasta-files.html#using-awk-instead-of-csplitsed" rel="nofollow noreferrer">https://crashcourse.housegordon.org/split-fasta-files.html#using-awk-instead-of-csplitsed</a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-05-12T12:49:55.047Z
Answers.LastActivityDate: 2023-08-26T20:59:58.800Z
Answers.LastEditDate: 2023-08-26T20:59:58.800Z
Answers.UserDisplayName: cmdoret
Answers.Body: <p>There are many ways to do it. Here is one way to do in Python.</p>
  
  <pre class="lang-python prettyprint-override"><code>import os
  
  with open(&quot;input.fasta&quot;) as f:
      for line in f:
          if line.startswith('&gt;'):
              record_name = line.lstrip(&quot;&gt;&quot;)
              outfilename = f&quot;{(record_name.rstrip())}.fasta&quot;
              if not os.path.exists(outfilename):
                  out = open(outfilename, 'w+')       
              else:
                  print('File already exists!')
          out.write(line)
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-09-07T02:48:32.470Z
Answers.LastActivityDate: 2023-09-07T02:48:32.470Z
Answers.UserDisplayName: Supertech
Answers.Body: <p>This worked for me today:</p>
  <pre class="lang-r prettyprint-override"><code># Load required packages
  BiocManager::install(&quot;Biostrings&quot;)
  
  library(Biostrings)
  
  # Read the multi-genome FASTA file
  multi_genome_fasta &lt;- readDNAStringSet(&quot;*.fasta&quot;)
  
  # Extract individual genomes and save as separate FASTA files
  for (i in 1:length(multi_genome_fasta)) {
      header &lt;- names(multi_genome_fasta)[i]
      sequence &lt;- as.character(multi_genome_fasta[i])
      
      # Combine header and sequence
      combined_data &lt;- paste(&quot;&gt;&quot;, header, sequence)
      
      # Save the combined data as a separate FASTA file
      file_name &lt;- paste0(header, &quot;.fasta&quot;)
      writeLines(combined_data, file_name)
      
      cat(&quot;Saved&quot;, header, &quot;as&quot;, file_name, &quot;\n&quot;)
  }
  
  cat(&quot;Separation completed.\n&quot;)
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-08-26T04:24:22.900Z
Answers.LastActivityDate: 2023-08-26T21:00:23.683Z
Answers.LastEditDate: 2023-08-26T21:00:23.683Z
Answers.UserDisplayName: Belinda
Body: <p>I have a file contain multiple sequence, and I want to separate them by &quot;gene:&quot; into different file.
  example:</p>
  <p><code>example.fa</code></p>
  <pre><code>&gt;KQK21959
  ATGGTGCTCGACCCCGTCGTCGGGGGCTCGGCCTCCCGCAAGGTCGAGCCCCTAACCCTA
  
  &gt;KQK14546
  ATGCCTCCGCCGGACGCGGCCACCTACGCTCCCACGCTGCCAATGGCGACGTACCTCCCA
  </code></pre>
  <p>How to get results like this? One sequence per file, and after <code>&gt;</code> is gene id, not cds id</p>
  <p><code>KQK21959.fa</code></p>
  <pre><code>&gt;KQK21959
  ATGGTGCTCGACCCCGTCGTCGGGGGCTCGGCCTCCCGCAAGGTCGAGCCCCTAACCCTA
  </code></pre>
  <p><code>KQK14546.fa</code></p>
  <pre><code>&gt;KQK14546
  ATGCCTCCGCCGGACGCGGCCACCTACGCTCCCACGCTGCCAATGGCGACGTACCTCCCA
  </code></pre>
  
Tags: <fasta><ngs><gene>
Title: Separate multiple sequence into different file, one sequence per file
ThreadText: # Separate multiple sequence into different file, one sequence per file
  
  (Asked by: username_0 on 2020-05-11)
  
  I have a file contain multiple sequence, and I want to separate them by "gene:" into different file.
  example:
  
  `example.fa`
  
  ```
  >KQK21959
  ATGGTGCTCGACCCCGTCGTCGGGGGCTCGGCCTCCCGCAAGGTCGAGCCCCTAACCCTA
  
  >KQK14546
  ATGCCTCCGCCGGACGCGGCCACCTACGCTCCCACGCTGCCAATGGCGACGTACCTCCCA
  
  ```
  
  How to get results like this? One sequence per file, and after `>` is gene id, not cds id
  
  `KQK21959.fa`
  
  ```
  >KQK21959
  ATGGTGCTCGACCCCGTCGTCGGGGGCTCGGCCTCCCGCAAGGTCGAGCCCCTAACCCTA
  
  ```
  
  `KQK14546.fa`
  
  ```
  >KQK14546
  ATGCCTCCGCCGGACGCGGCCACCTACGCTCCCACGCTGCCAATGGCGACGTACCTCCCA
  
  ```
  
  **Tags:** fasta, ngs, gene
  
  
  ---
  
  ## 6 answers
  
  ### Answer by username_1 on 2020-05-12. Score: 3
  
  A simple Biopython solution:
  
  ```py
  from Bio import SeqIO
  
  for record in SeqIO.parse("example.fa", "fasta"):
      SeqIO.write(record, record.id + ".fa", "fasta")
  
  ```
  
  Note, if you have multiple sequences with the same id, only the last sequence will be kept in the final output files
  
  > **Comments:**
  > **username_0**: Thank you! It works excellent.  
  
  ---
  
  ### Answer by username_2 on 2020-05-12. Score: 3
  
  There's an app for that! The `exonerate` package (see [here](https://www.ebi.ac.uk/about/vertebrate-genomics/software/exonerate)) includes a nice `fastaexplode` command that does exactly what you're looking for and will be much, much faster than anything we give you here since it is written in C and not a scripting language. Just install `exonerate` (you can do that with `sudo apt install exonerate` on Debian-based systems) and then:
  
  ```
  fastaexplode file.fa
  
  ```
  
  This will create these two files (`file.fa` is the original input file from your question):
  
  ```
  $ ls
  file.fa  KQK14546.fa  KQK21959.fa
  
  ```
  
  
  ---
  
  ### Answer by username_3 on 2020-05-12. Score: 2
  
  That really depends on the tools you are using. If anything will do you can use the following python snippet.
  
  If you know that each sequence is on a single line and your file isnt gigantic use this
  
  # EDIT
  
  Updated so the file isn't read to memory at once to address @username_2 point. Although, the above solutions are probably much better.
  
  ```py
  with open( "seqs.fasta" ) as f:
      out = ""
      
      for line in f:
          if not line.strip(): continue 
          if line.startswith( ">" ):
              if not type( out ) == str: out.close()
              gene = line[1:].strip().split()[0]
              out = open( f"{gene}.fa", "w" )
              out.write( line )
              continue 
          out.write( line.strip() )
      
  
  ```
  
  
  ---
  
  ### Answer by username_4 on 2020-05-12. Score: 2
  
  This can also be done using awk. This is harder to read, but probably faster than python:
  
  ```bash
  awk 'sub(/^>/,""){
          FILE=$0".fa"; 
      print ">"$0 >FILE; 
          next
      }{print > FILE}' file.fa. 
  
  ```
  
  This will define a new output file `FILE` at each header line, whose filename is the header minus the `>` character, suffixed with `.fa`. And all lines in the file are appended to the current output file.
  
  EDIT: Changed to a faster version found on: <https://crashcourse.housegordon.org/split-fasta-files.html#using-awk-instead-of-csplitsed>
  
  
  ---
  
  ### Answer by username_5 on 2023-09-07. Score: 2
  
  There are many ways to do it. Here is one way to do in Python.
  
  ```python
  import os
  
  with open("input.fasta") as f:
      for line in f:
          if line.startswith('>'):
              record_name = line.lstrip(">")
              outfilename = f"{(record_name.rstrip())}.fasta"
              if not os.path.exists(outfilename):
                  out = open(outfilename, 'w+')       
              else:
                  print('File already exists!')
          out.write(line)
  
  ```
  
  
  ---
  
  ### Answer by username_6 on 2023-08-26. Score: 2
  
  This worked for me today:
  
  ```r
  # Load required packages
  BiocManager::install("Biostrings")
  
  library(Biostrings)
  
  # Read the multi-genome FASTA file
  multi_genome_fasta <- readDNAStringSet("*.fasta")
  
  # Extract individual genomes and save as separate FASTA files
  for (i in 1:length(multi_genome_fasta)) {
      header <- names(multi_genome_fasta)[i]
      sequence <- as.character(multi_genome_fasta[i])
      
      # Combine header and sequence
      combined_data <- paste(">", header, sequence)
      
      # Save the combined data as a separate FASTA file
      file_name <- paste0(header, ".fasta")
      writeLines(combined_data, file_name)
      
      cat("Saved", header, "as", file_name, "\n")
  }
  
  cat("Separation completed.\n")
  
  ```
  
  
  ---
  
  