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.
Importing packages
Section titled “Importing packages”Before using a package, you need to import it. Python offers several ways to do this.
import
Section titled “import”The simplest approach imports the entire module.
import os
print(os.getcwd())/home/user/projects/rna_seq_analysisYou then access functions and classes using the module name as a prefix.
from … import
Section titled “from … import”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.gzsample_data.fastq.gzPath is very useful for working with file paths in bioinformatics pipelines. It handles path separators across operating systems automatically.
Aliases
Section titled “Aliases”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.0100.4987562112089You 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.
Standard library highlights
Section titled “Standard library highlights”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 |
collections.Counter
Section titled “collections.Counter”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)]csv module
Section titled “csv module”Many bioinformatics tools produce tab-separated output files. The csv module handles both CSV and TSV formats.
import csvimport 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.001BRCA1: log2fc=-1.8, p=0.003EGFR: log2fc=3.2, p=0.0001DictReader maps each row to a dictionary using the header as keys. This makes your code more readable than indexing by column number.
Installing packages with uv
Section titled “Installing packages with uv”This project uses uv for Python package management. Do not use pip install directly. uv is faster, more reliable, and handles virtual environments automatically.
Setting up a new project
Section titled “Setting up a new project”First, create a project directory and initialize it with uv.
mkdir gene_analysiscd gene_analysisuv initThis creates a pyproject.toml file and a .venv/ virtual environment.
Adding packages
Section titled “Adding packages”Use uv add to install packages. This updates your pyproject.toml automatically.
uv add pandas numpyYou can add multiple packages at once. Each package and its version will be recorded in pyproject.toml.
Running scripts
Section titled “Running scripts”Use uv run to execute scripts in the correct environment.
uv run python script.pyThis ensures Python uses the packages installed in your project’s virtual environment.
pyproject.toml
Section titled “pyproject.toml”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.
Key bioinformatics packages
Section titled “Key bioinformatics 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.
Virtual environments
Section titled “Virtual environments”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:
source .venv/bin/activateEach project should have its own virtual environment. Never install packages into your system Python.
Quick reference
Section titled “Quick reference”| 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 |
Next steps
Section titled “Next steps”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.