Skip to content

Working with Packages

Python comes with a standard library of built-in modules. These cover common tasks like file handling, math, and text processing. For specialized work like data analysis or bioinformatics, you will need third-party packages from PyPI. PyPI hosts over 500,000 packages that extend what Python can do.

Before using a package, you need to import it. Python offers several ways to do this.

The simplest approach imports the entire module.

import os
print(os.getcwd())
/home/user/projects/rna_seq_analysis

You then access functions and classes using the module name as a prefix.

You can import specific items from a module. This lets you use them directly without the module prefix.

from pathlib import Path
p = Path("sample_data.fastq.gz")
print(p.stem)
print(p.suffix)
print(p.name)
sample_data.fastq
.gz
sample_data.fastq.gz

Path is very useful for working with file paths in bioinformatics pipelines. It handles path separators across operating systems automatically.

Some packages have long names. The community has adopted standard short aliases for common packages. Use the as keyword to create an alias.

import numpy as np
counts = np.array([100, 250, 50, 300, 75])
print(counts)
print(counts.mean())
print(counts.std())
[100 250 50 300 75]
155.0
100.4987562112089

You will see np for NumPy, pd for pandas, and plt for matplotlib in nearly every tutorial and codebase. Stick with these conventions so your code is readable to others.

The standard library includes many useful modules. Here are a few that come up often in bioinformatics work.

Module Purpose
os Interact with the operating system, environment variables
pathlib Object-oriented file path handling
csv Read and write CSV/TSV files
collections Specialized container types like Counter and defaultdict
gzip Read and write gzip-compressed files
json Parse and write JSON data
sys Access command-line arguments and system info

Counter tallies how often each item appears in a list. This is handy for counting gene occurrences, k-mers, or any repeated elements.

from collections import Counter
gene_list = ["TP53", "BRCA1", "TP53", "EGFR", "BRCA1", "TP53"]
gene_counts = Counter(gene_list)
print(gene_counts)
print(gene_counts.most_common(2))
Counter({'TP53': 3, 'BRCA1': 2, 'EGFR': 1})
[('TP53', 3), ('BRCA1', 2)]

Many bioinformatics tools produce tab-separated output files. The csv module handles both CSV and TSV formats.

import csv
import io
tsv_data = "gene\tlog2fc\tpvalue\nTP53\t2.5\t0.001\nBRCA1\t-1.8\t0.003\nEGFR\t3.2\t0.0001"
reader = csv.DictReader(io.StringIO(tsv_data), delimiter="\t")
for row in reader:
print(f"{row['gene']}: log2fc={row['log2fc']}, p={row['pvalue']}")
TP53: log2fc=2.5, p=0.001
BRCA1: log2fc=-1.8, p=0.003
EGFR: log2fc=3.2, p=0.0001

DictReader maps each row to a dictionary using the header as keys. This makes your code more readable than indexing by column number.

This project uses uv for Python package management. Do not use pip install directly. uv is faster, more reliable, and handles virtual environments automatically.

First, create a project directory and initialize it with uv.

Terminal window
mkdir gene_analysis
cd gene_analysis
uv init

This creates a pyproject.toml file and a .venv/ virtual environment.

Use uv add to install packages. This updates your pyproject.toml automatically.

Terminal window
uv add pandas numpy

You can add multiple packages at once. Each package and its version will be recorded in pyproject.toml.

Use uv run to execute scripts in the correct environment.

Terminal window
uv run python script.py

This ensures Python uses the packages installed in your project’s virtual environment.

After running uv init and adding some packages, your pyproject.toml will look something like this:

[project]
name = "gene-analysis"
version = "0.1.0"
description = ""
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=2.2.4",
"pandas>=2.2.3",
]

This file is the single source of truth for your project’s dependencies. When you share your project, others can run uv sync to install all the same packages.

These are the most commonly used third-party packages in bioinformatics and data science.

Package Purpose Install command
pandas Tabular data manipulation uv add pandas
polars Fast DataFrame library for large datasets uv add polars
numpy Numerical arrays and math operations uv add numpy
scipy Statistical tests and scientific computing uv add scipy
scikit-learn Machine learning algorithms uv add scikit-learn
scanpy Single-cell RNA-seq analysis uv add scanpy
pysam Read and write BAM/SAM/VCF files uv add pysam
biopython Sequence analysis, BLAST parsing, file I/O uv add biopython
matplotlib General-purpose plotting uv add matplotlib
seaborn Statistical data visualization uv add seaborn

You do not need all of these at once. Add packages as your project requires them.

A virtual environment is an isolated Python installation for a single project. It prevents packages from one project from interfering with another.

When you run uv init, it creates a .venv/ directory inside your project folder. This directory contains the Python interpreter and all installed packages for that project.

You do not need to activate the virtual environment manually. Running uv run python script.py handles this for you. If you want to activate it yourself for interactive use, run:

Terminal window
source .venv/bin/activate

Each project should have its own virtual environment. Never install packages into your system Python.

Task Command
Create a new project uv init
Add a package uv add <package>
Add multiple packages uv add pandas numpy scipy
Remove a package uv remove <package>
Run a script uv run python script.py
Sync dependencies from pyproject.toml uv sync
Import a module import module_name
Import a specific item from module import item
Import with alias import numpy as np

Now that you know how to install and import packages, you are ready to work with tabular data. Head to Pandas Essentials to learn how to load, filter, and analyze data with pandas.