-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaverage_read_length.py
63 lines (50 loc) · 1.58 KB
/
average_read_length.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python3
"""
average_read_length.py
This script outputs the average read length of a FASTA or FASTQ file
"""
import sys
if len(sys.argv) != 2:
print("Usage: python average_read_length.py <file_name>")
sys.exit(1)
file_path = sys.argv[1]
try:
# Open the file specified as a positional argument
with open(file_path, 'r') as file:
# Read the first character
first_char = file.read(1)
# Check if its FASTA or FASTQ file
if first_char == ">":
file_type = "fasta"
elif first_char == "@":
file_type = "fastq"
else:
print("ERROR: file must be FASTA or FASTQ file without header")
sys.exit(1)
# Explicitly close the file
file.close()
except FileNotFoundError:
print(f"The file '{file_path}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
print("COMPUTE MEAN READ LENGTH FROM FASTA FILE\n")
n_reads = 0
total_length = 0
if file_type == "fasta":
with open(file_path, "r") as f_in:
for line in f_in:
if line.startswith(">"):
n_reads += 1
else:
total_length += len(line.strip())
elif file_type == "fastq":
next_line = False
with open(file_path, "r") as f_in:
for line in f_in:
if line.startswith("@"):
next_line = True
n_reads += 1
elif next_line:
total_length += len(line.strip())
next_line = False
print("\nMean read length:", round((total_length/n_reads), 3))