-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastq2fasta.py
executable file
·166 lines (123 loc) · 4.34 KB
/
fastq2fasta.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# ------------------------------------------------------------
# Script converts fastq files to fasta format
#-------------------------------------------------------------
__version__ = "1.0.a"
__last_update_date__ = "2020-04-13"
import sys
if sys.version_info.major < 3:
print( "\nYour python interpreter version is " + "%d.%d" % (sys.version_info.major,
sys.version_info.minor) )
print(" Please, use Python 3.\a")
# In python 2 'raw_input' does the same thing as 'input' in python 3.
# Neither does 'input' in python2.
if sys.platform.startswith("win"):
raw_input("Press ENTER to exit:")
# end if
sys.exit(1)
# end if
import os
def platf_depend_exit(exit_code=0):
"""
Function asks to press ENTER press on Windows
and exits after that.
:type exit_code: int;
"""
if sys.platform.startswith("win"):
input("Press ENTER to exit:")
# end if
sys.exit(exit_code)
# end def platf_depend_exit
def print_help():
print("\nScript 'fastq2fasta.py' converts fastq files to fasta format.\n")
print("Version {}; {} edition.".format(__version__, __last_update_date__))
print("\nUsage:")
print(" python3 fastq2fasta.py first.fastq second.fastq.gz third.fq.gz")
print("Following command will process all *.fasta(.gz) and *.fa(.gz) files in the working directory:")
print(" python3 fastq2fasta.py")
print("\nOptions:")
print(" -h (--help): print help message.")
print(" -v (--version): print version.")
# end if
# First check for information-providing flags
if "-h" in sys.argv[1:] or "--help" in sys.argv[1:]:
print_help()
platf_depend_exit()
# end if
if "-v" in sys.argv[1:] or "--version" in sys.argv[1:]:
print(__version__)
platf_depend_exit()
# end if
fpaths = list()
from re import search as re_search
is_fastq = lambda f: False if re_search(r".*\.f(ast)?q(\.gz)?$", f) is None else True
# Add command line arguments to list of fpaths and check them
valid_options = ("-h", "--help", "-v", "--version")
for arg in sys.argv[1:]:
if not arg in valid_options:
if not os.path.exists(arg):
print("File '{}' does not exist!".format(arg))
platf_depend_exit(1)
# end if
if not is_fastq(arg):
print("File '{}' does not look like a fastq file".format(arg))
print("Script understands only '*.fastq(.gz)'' and '*.fq(.gz)' extentions")
platf_depend_exit(1)
# end if
fpaths.append(arg)
# end for
del valid_options
# If no input files are specified -- process all fastq files in the working directory
if len(fpaths) == 0:
fpaths = tuple( filter(is_fastq, os.listdir('.')) )
# end if
if len(fpaths) == 0:
print_help()
platf_depend_exit(1)
# end if
print("fastq2fasta. Version {}; {} edition\n".format(__version__, __last_update_date__))
print('Following files are found and will be processed:')
for f in fpaths:
print(os.path.abspath(f))
print('-' * 25 + '\n')
import gzip
LINES_IN_READ = 4 # 4 lines per recoed in fastq format
is_gzipped = lambda file: True if file.endswith(".gz") else False
# Start converting files:
for i, fpath in enumerate(fpaths):
read_counter = 0
if is_gzipped(fpath):
# For writing bytes to file(s)
open_func = gzip.open
gt_chr = b'>'
out_mode = "wb"
else:
# For writing strings to file(s)
open_func = open
gt_chr = '>'
out_mode = "w"
# end if
outfpath = re_search(r"(.+)\.f(ast)?q(.gz)?$", fpath).group(1) + ".fasta"
with open_func(fpath) as infile, open(outfpath, out_mode) as outfile:
read_counter = 0
# k == 1: Sequence name; k == 2: Sequence itself;
# k == 3: Comment line; k == 4: Quality line;
k = 1
for line in infile:
if k == 1: # write sequence name
line = gt_chr + line[1:]
outfile.write(line)
elif k == 2: # write sequence line
outfile.write(line)
elif k == 4: # reset counter
k = 0
# end if
k += 1
read_counter += 1
# end for
# end with
print("{}. '{}' ({} reads) --> fasta".format(i+1, os.path.basename(fpath), read_counter // LINES_IN_READ))
# end for
print("\nCompleted!")
platf_depend_exit()