To extract the start and end positions of genes along with their strand information from a GenBank file (sega007.gb) and export them to a TSV (Tab-Separated Values) file, you can use the following Python script with Biopython:
Python Script:
from Bio import SeqIO
# Input and output file names
input_file = "sega007.gb"
output_file = "gene_positions.tsv"
# Open the output file for writing
with open(output_file, 'w') as out_handle:
# Write the header
out_handle.write("Gene_ID\tStart\tEnd\tStrand\n")
# Parse the GenBank file
for record in SeqIO.parse(input_file, "genbank"):
for feature in record.features:
if feature.type == "gene":
# Extract gene ID (or use locus_tag if available)
gene_id = feature.qualifiers.get("gene", [""])[0]
if not gene_id:
gene_id = feature.qualifiers.get("locus_tag", [""])[0]
# Extract start, end, and strand
start = feature.location.start + 1 # GenBank uses 0-based, convert to 1-based
end = feature.location.end
strand = feature.location.strand
# Write to the output file
out_handle.write(f"{gene_id}\t{start}\t{end}\t{strand}\n")
print(f"Gene positions and strand information have been exported to {output_file}")
Explanation:
-
Input/Output Files:
input_file: Your GenBank file (sega007.gb).
output_file: The TSV file (gene_positions.tsv) where the results will be saved.
-
Header:
- The TSV file will have columns:
Gene_ID, Start, End, and Strand.
-
Parsing the GenBank File:
- The script uses
SeqIO.parse to read the GenBank file.
- It iterates over all features and checks for features of type
"gene".
-
Extracting Information:
Gene_ID: Uses the gene qualifier if available; otherwise, falls back to locus_tag.
Start and End: The start and end positions of the gene. Note that GenBank uses 0-based indexing, so +1 is added to the start position to convert it to 1-based.
Strand: The strand information (1 for forward, -1 for reverse).
-
Output:
- The results are written to the TSV file in the specified format.
How to Run:
- Ensure you have Biopython installed. If not, install it using:
pip install biopython
- Save the script to a file (e.g.,
extract_gene_positions.py).
- Run the script:
python extract_gene_positions.py
- The output will be saved in
gene_positions.tsv.
Example Output:
Gene_ID Start End Strand
gene1 100 500 1
gene2 600 1200 -1
gene3 1500 2000 1