bio-write-sequences

Write biological sequences to files (FASTA, FASTQ, GenBank, EMBL) using Biopython Bio.SeqIO. Use when saving sequences, creating new sequence files, or outputting modified records.

1,802 stars

Best use case

bio-write-sequences is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Write biological sequences to files (FASTA, FASTQ, GenBank, EMBL) using Biopython Bio.SeqIO. Use when saving sequences, creating new sequence files, or outputting modified records.

Teams using bio-write-sequences should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/bio-write-sequences/SKILL.md --create-dirs "https://raw.githubusercontent.com/FreedomIntelligence/OpenClaw-Medical-Skills/main/skills/bio-write-sequences/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/bio-write-sequences/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How bio-write-sequences Compares

Feature / Agentbio-write-sequencesStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Write biological sequences to files (FASTA, FASTQ, GenBank, EMBL) using Biopython Bio.SeqIO. Use when saving sequences, creating new sequence files, or outputting modified records.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

## Version Compatibility

Reference examples tested with: BioPython 1.83+, pysam 0.22+, samtools 1.19+

Before using code patterns, verify installed versions match. If versions differ:
- Python: `pip show <package>` then `help(module.function)` to check signatures

If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.

# Write Sequences

**"Write sequences to a file"** → Serialize SeqRecord objects into a formatted sequence file.
- Python: `SeqIO.write()` (BioPython)
- R: `writeXStringSet()` (Biostrings)

Write SeqRecord objects to sequence files using Biopython's Bio.SeqIO module.

## Required Import

```python
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
```

## Core Functions

### SeqIO.write() - Write Records to File
Write one or more SeqRecord objects to a file.

```python
SeqIO.write(records, 'output.fasta', 'fasta')
```

**Parameters:**
- `records` - Single SeqRecord, list, or iterator of SeqRecords
- `handle` - Filename (string) or file handle
- `format` - Output format string

**Returns:** Number of records written (integer)

### record.format() - Get Formatted String
Get a string representation without writing to file.

```python
formatted = record.format('fasta')
print(formatted)
```

## Creating SeqRecord Objects

**Goal:** Construct in-memory sequence records suitable for writing to any format.

**Approach:** Create `SeqRecord` with at minimum a `Seq` and `id`. Add `letter_annotations` for FASTQ, `annotations['molecule_type']` for GenBank/EMBL.

**"Create a sequence record from scratch"** → Wrap a `Seq` string in a `SeqRecord` with metadata fields.
- Python: `SeqRecord(Seq(...), id=...)` (BioPython)

### Minimal SeqRecord
```python
record = SeqRecord(Seq('ATGCGATCGATCG'), id='seq1')
```

### Full SeqRecord
```python
record = SeqRecord(
    Seq('ATGCGATCGATCG'),
    id='seq1',
    name='sequence_one',
    description='Example sequence for demonstration'
)
```

### With Annotations (for GenBank output)
```python
from Bio.SeqFeature import SeqFeature, FeatureLocation

record = SeqRecord(
    Seq('ATGCGATCGATCG'),
    id='seq1',
    annotations={'molecule_type': 'DNA'}
)
record.features.append(
    SeqFeature(FeatureLocation(0, 9), type='gene', qualifiers={'gene': ['exampleGene']})
)
```

## Common Formats

| Format | String | Notes |
|--------|--------|-------|
| FASTA | `'fasta'` | Most universal, sequence + header only |
| FASTQ | `'fastq'` | Requires quality scores in letter_annotations |
| GenBank | `'genbank'` | Requires annotations and molecule_type |
| EMBL | `'embl'` | Similar requirements to GenBank |
| Tab | `'tab'` | Simple ID + sequence tabular format |

## Code Patterns

### Write Single Record
```python
record = SeqRecord(Seq('ATGC'), id='my_seq', description='test sequence')
SeqIO.write(record, 'output.fasta', 'fasta')
```

### Write Multiple Records
```python
records = [
    SeqRecord(Seq('ATGC'), id='seq1'),
    SeqRecord(Seq('GCTA'), id='seq2'),
    SeqRecord(Seq('TTAA'), id='seq3')
]
count = SeqIO.write(records, 'output.fasta', 'fasta')
print(f'Wrote {count} records')
```

### Write to File Handle
```python
with open('output.fasta', 'w') as handle:
    SeqIO.write(records, handle, 'fasta')
```

### Write Modified Records

**Goal:** Transform sequences in-memory and write the modified versions to a new file.

**Approach:** Parse input, apply transformation via generator, write output. Using a generator avoids loading all records into memory.

**"Modify sequences and save"** → Parse records, transform each, write to new file with `SeqIO.write()`.

```python
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord

def uppercase_record(rec):
    return SeqRecord(rec.seq.upper(), id=rec.id, description=rec.description)

records = SeqIO.parse('input.fasta', 'fasta')
modified = (uppercase_record(rec) for rec in records)
SeqIO.write(modified, 'output.fasta', 'fasta')
```

### Append to Existing File
```python
with open('output.fasta', 'a') as handle:
    SeqIO.write(new_records, handle, 'fasta')
```

### Write FASTQ with Quality Scores
```python
record = SeqRecord(Seq('ATGCGATCG'), id='read1')
record.letter_annotations['phred_quality'] = [30, 30, 28, 25, 30, 30, 28, 25, 30]
SeqIO.write(record, 'output.fastq', 'fastq')
```

### Write GenBank Format
```python
record = SeqRecord(Seq('ATGCGATCGATCG'), id='SEQ001', name='example')
record.annotations['molecule_type'] = 'DNA'
record.annotations['topology'] = 'linear'
record.annotations['organism'] = 'Example organism'
SeqIO.write(record, 'output.gb', 'genbank')
```

## Common Errors

| Error | Cause | Solution |
|-------|-------|----------|
| `TypeError: SeqRecord expected` | Passed raw string/Seq | Wrap in SeqRecord object |
| `ValueError: missing molecule_type` | GenBank without annotations | Add `record.annotations['molecule_type'] = 'DNA'` |
| `ValueError: missing quality scores` | FASTQ without phred_quality | Add quality scores to letter_annotations |
| `ValueError: Sequences must all be the same length` | PHYLIP with unequal lengths | Pad or trim sequences first |

## Format-Specific Requirements

### FASTQ
Must have quality scores:
```python
record.letter_annotations['phred_quality'] = [30] * len(record.seq)
```

### GenBank/EMBL
Must have molecule_type:
```python
record.annotations['molecule_type'] = 'DNA'  # or 'RNA', 'protein'
```

### PHYLIP
All sequences must be same length. IDs truncated to 10 characters.

## Related Skills

- read-sequences - Read sequences before modifying and writing
- format-conversion - Direct format conversion without intermediate processing
- filter-sequences - Filter sequences before writing subset
- sequence-manipulation/seq-objects - Create SeqRecord objects to write
- alignment-files - For SAM/BAM output, use samtools/pysam

Related Skills

bio-read-sequences

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Read biological sequence files (FASTA, FASTQ, GenBank, EMBL, ABI, SFF) using Biopython Bio.SeqIO. Use when parsing sequence files, iterating multi-sequence files, random access to large files, or high-performance parsing.

bio-filter-sequences

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Filter and select sequences by criteria (length, ID, GC content, patterns) using Biopython. Use when subsetting sequences, removing unwanted records, or selecting by specific criteria.

bio-consensus-sequences

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Generate consensus FASTA sequences by applying VCF variants to a reference using bcftools consensus. Use when creating sample-specific reference sequences or reconstructing haplotypes.

zinc-database

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Access ZINC (230M+ purchasable compounds). Search by ZINC ID/SMILES, similarity searches, 3D-ready structures for docking, analog discovery, for virtual screening and drug discovery.

zarr-python

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Chunked N-D arrays for cloud storage. Compressed arrays, parallel I/O, S3/GCS integration, NumPy/Dask/Xarray compatible, for large-scale scientific computing pipelines.

xlsx

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.

writing-skills

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Use when creating new skills, editing existing skills, or verifying skills work before deployment

writing-plans

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Use when you have a spec or requirements for a multi-step task, before touching code

wikipedia-search

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Search and fetch structured content from Wikipedia using the MediaWiki API for reliable, encyclopedic information

wellally-tech

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

Integrate digital health data sources (Apple Health, Fitbit, Oura Ring) and connect to WellAlly.tech knowledge base. Import external health device data, standardize to local format, and recommend relevant WellAlly.tech knowledge base articles based on health data. Support generic CSV/JSON import, provide intelligent article recommendations, and help users better manage personal health data.

weightloss-analyzer

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

分析减肥数据、计算代谢率、追踪能量缺口、管理减肥阶段

<!--

1802
from FreedomIntelligence/OpenClaw-Medical-Skills

# COPYRIGHT NOTICE