<p>as far as I understand your question, you want to reformat your output file that consists of two columns:</p>
<pre><code>QRv313_NP342_d0_h2_l9    YN13213
</code></pre>
<p>to extract the second &quot;field&quot; from your first column, where fields are delimited by <code>_</code>:</p>
<pre><code>NP342    YN13213
</code></pre>
<p>In general, your code is close. You could just split again by <code>_</code>:</p>
<pre class="lang-py prettyprint-override"><code>import sys
file_object = open(sys.argv[1])

for my_data in file_object:
  list =  my_data.strip().split(&quot;\t&quot;)
  print (list[0].split(&quot;_&quot;)[1], list[1], sep=&quot;\t&quot;)
</code></pre>
<p>Now when I teach students, I usually tell them to always expect the unexpected, so you might also want to add some minimal error checking, so here's a version that checks some
minimal assumptions:</p>
<pre class="lang-py prettyprint-override"><code>
from sys import argv
from os import path

usage = f&quot;&quot;&quot;
usage: {argv[0]} &lt;blast_output&gt;
&quot;&quot;&quot;


def main(in_file):
    with open(argv[1], &quot;r&quot;) as in_handle:
        for lno, line in enumerate(in_handle):
            line = line.strip()
            cols = line.split(&quot;\t&quot;)
            if len(cols) != 2:
                raise ValueError(
                    f&quot;Error in line {lno}: Expected two columns,&quot;
                    &quot; found {len(cols)}. Offending line: {cols}&quot;
                )
            query = cols[0].split(&quot;_&quot;)
            if len(query) != 5:
                raise ValueError(
                    f&quot;Error in line {lno}: Expected five fields&quot;
                    &quot;in query string, found {len(query)}. Offending line {query}&quot;
                )
            print(query[1], cols[1], sep=&quot;\t&quot;)


if __name__ == &quot;__main__&quot;:
    if len(argv) != 2:
        print(usage)
        raise ValueError(&quot;Illegal number of arguments&quot;)
    if not path.exists(argv[1]):
        raise FileNotFoundError(f&quot;File {argv[1]} could not be found. Check spelling&quot;)

    main(argv[1])
</code></pre>
<p>And this is what it produces:</p>
<pre><code>&gt;python3 ex.py in.txt
NP342   YN13213
NP9080  YN5345
NP123   YN756
NP123   YN9768
NP654   YN432
NP8     YN3242
NP756   YN85686
</code></pre>

CC BY-SA 4.0
2020-11-29T20:32:58.620Z
Yup, that was a typo. The keyword is meant to be `sep="\t"`. Corrected in the script
Bastian Schiffthaler
CC BY-SA 4.0
2020-11-30T11:25:27.937Z
Keep track of the ID's you've encountered within python and perform any filtering you want according to that. Basic python programming is outside the scope of this site.
Devon Ryan
CC BY-SA 4.0
2020-11-29T10:47:46.420Z
2020-11-29T20:32:22.317Z
2020-11-29T20:32:22.317Z
Bastian Schiffthaler
<p>I have a blast file produced. I executed a <code>blast(x)</code> command outputting both <code>&quot;qeseqid&quot;</code> and <code>&quot;sseqid&quot;</code>:</p>
<pre><code>QRv313_NP342_d0_h2_l9    YN13213
QRv313_NP9080_d0_h1_l1   YN5345
QRv313_NP123_d0_h1_l7    YN756
QRv313_NP123_d0_h1_l113  YN9768
QRv313_NP654_d0_h2_l6    YN432
QRv313_NP8_d0_h1_l1      YN3242
QRv313_NP756_d0_h1_l2    YN85686
</code></pre>
<p>I have written a command in <code>nano</code> within <code>command-line</code> to obtain the following desired output:</p>
<pre><code>NP342    YN13213
NP9080   YN5345
NP123    YN756
NP123    YN9768
NP654    YN432
NP8_d0   YN3242
NP756    YN85686
</code></pre>
<p>I have written a <code>nano</code> script to provide me a tab delimited column of my query and subject id. I am just having trouble moving forward from here. I am unsure as to how I would modify my script to provide me with my desired output.</p>
<pre><code>import sys
file_object = open(sys.argv[1])

for my_data in file_object:

  list =  my_data.split(&quot;\t&quot;)

  print (list [0], list [1])
</code></pre>
<p>Is there a way t alter my command so I can receive the desired output?</p>
<p>Any suggestions would be kindly appreciated!</p>

<python><file-formats>
Creating a tab delimited column
# Creating a tab delimited column

(Asked by: username_0 on 2020-11-29)

I have a blast file produced. I executed a blast(x) command outputting both "qeseqid" and "sseqid":
QRv313_NP342_d0_h2_l9    YN13213
QRv313_NP9080_d0_h1_l1   YN5345
QRv313_NP123_d0_h1_l7    YN756
QRv313_NP123_d0_h1_l113  YN9768
QRv313_NP654_d0_h2_l6    YN432
QRv313_NP8_d0_h1_l1      YN3242
QRv313_NP756_d0_h1_l2    YN85686

I have written a command in nano within command-line to obtain the following desired output:
NP342    YN13213
NP9080   YN5345
NP123    YN756
NP123    YN9768
NP654    YN432
NP8_d0   YN3242
NP756    YN85686

I have written a nano script to provide me a tab delimited column of my query and subject id. I am just having trouble moving forward from here. I am unsure as to how I would modify my script to provide me with my desired output.
import sys
file_object = open(sys.argv[1])

for my_data in file_object:

  list =  my_data.split("\t")

  print (list [0], list [1])

Is there a way t alter my command so I can receive the desired output?
Any suggestions would be kindly appreciated!

**Tags:** python, file-formats

---

## 1 answers

### Answer by username_1 on 2020-11-29. Score: 3 | Accepted answer

as far as I understand your question, you want to reformat your output file that consists of two columns:
QRv313_NP342_d0_h2_l9    YN13213

to extract the second "field" from your first column, where fields are delimited by _:
NP342    YN13213

In general, your code is close. You could just split again by _:
import sys
file_object = open(sys.argv[1])

for my_data in file_object:
  list =  my_data.strip().split("\t")
  print (list[0].split("_")[1], list[1], sep="\t")

Now when I teach students, I usually tell them to always expect the unexpected, so you might also want to add some minimal error checking, so here's a version that checks some
minimal assumptions:

from sys import argv
from os import path

usage = f"""
usage: {argv[0]} 
"""


def main(in_file):
    with open(argv[1], "r") as in_handle:
        for lno, line in enumerate(in_handle):
            line = line.strip()
            cols = line.split("\t")
            if len(cols) != 2:
                raise ValueError(
                    f"Error in line {lno}: Expected two columns,"
                    " found {len(cols)}. Offending line: {cols}"
                )
            query = cols[0].split("_")
            if len(query) != 5:
                raise ValueError(
                    f"Error in line {lno}: Expected five fields"
                    "in query string, found {len(query)}. Offending line {query}"
                )
            print(query[1], cols[1], sep="\t")


if __name__ == "__main__":
    if len(argv) != 2:
        print(usage)
        raise ValueError("Illegal number of arguments")
    if not path.exists(argv[1]):
        raise FileNotFoundError(f"File {argv[1]} could not be found. Check spelling")

    main(argv[1])

And this is what it produces:
>python3 ex.py in.txt
NP342   YN13213
NP9080  YN5345
NP123   YN756
NP123   YN9768
NP654   YN432
NP8     YN3242
NP756   YN85686

> **Comments:**
> **username_1**: Yup, that was a typo. The keyword is meant to be `sep="\t"`. Corrected in the script  
> **username_2**: Keep track of the ID's you've encountered within python and perform any filtering you want according to that. Basic python programming is outside the scope of this site.  

---

