This is a test version of Biostars. For the public version, visit https://www.biostars.org.
add same string to the certain lines in python

Hi, a stupid question from a python beginner I'd like to rename the query of my fasta file, here is my sequence :

>WP_015529149.1
MSMTGIILAAVVVGGTGLFIGVFLGIAGKKFAVKVDEREEAILGVLPGNNCGGCGYAGCSGLAAAIVKGEAEVSGCPVGG
APVAAKIGDIMGVAAGTQERQTAFVKCAGTCEKAILDYDYTGIQDCTMASMMQNGGAKGCNSGCLGFGSCVAACPFDAIH
VVDGIAVVDKEACKACGKCIAACPKHLIELIPYEQKTFVRCNSNAKGKVQLTICQAGCIGCRLCEKNCEAGAITVTNFLA
HIDADKCTECGVCVEKCPRKIITLR
>WP_055172573.1
MSMTGIILAAVVVGGTGLFIGVFLGIAGKKFAVKVDEREEAILGVLPGNNCGGCGYAGCSGLAAAIVKGEAEVSGCPVGG
APVAAKIGEIMGVAAGTQERQTAFVKCAGTCEKAILDYDYTGIQDCTMASMMQNGGAKGCNSGCLGFGSCVAACPFDAIH
VVDGIAVVDKEACKACGKCIAACPKHLIELIPYEQKTFVRCNSNAKGKIQLTICQAGCIGCRICEKNCEAGAITVTNFLA
HIDADKCTECGVCVEKCPRKIITLR

I would like to add string "_ABCDE" to the line with ">"
to get" >WP_015529149.1_ABCDE" and" >WP_055172573.1_ABCDE", if I use python how to achieve this?

python

2 answers

with open("input.txt") as file:
    for i in file.readlines():
        if i.startswith(">"):
            print(str(i)+"_ABCDE")
        else:
            print(str(i))

Looking good, although for biiiiig files you shouldn't use .readlines() because you are reading everything in memory, while you can just iterate over the file:

with open("input.txt") as f:
    for i in f:
        if i.startswith(">"):
            print(str(i)+"_ABCDE"
        else:
            print(str(i))

Another way (for fun) using sed in Ubuntu:

sed '/>/ s/$/_ABCDE/' file.txt

The />/ matches the ">" pattern, while s/$/_ABCDE/ replaces the end of the line with _ABCDE.

Log in to answer this question.