Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readline() returns bracket

I wrote some codes to get some lines from .txt like below and its keep returning lines with brackets which I did not intend. Could you help me?

codes:

#!/bin/python
i=1
f=open("name.txt","r")
while(i<=225):
 x=f.readline().splitlines()
 print("mol new %s.bgf"%(x))
 i+=1
f.close()

name.txt

02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c
04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c
09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c
17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c
18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c

And it returns

mol new ['02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c'].bgf
mol new ['04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c'].bgf
mol new ['09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c'].bgf
mol new ['17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c'].bgf
mol new ['18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c'].bgf
like image 569
SIMONSON92 Avatar asked Jan 06 '23 14:01

SIMONSON92


2 Answers

Making minimal changes to your code, try:

i=1
f=open("name.txt","r")
while(i<=225):
 x=f.readline().rstrip('\n')
 print("mol new %s.bgf"%(x))
 i+=1
f.close()

This produces output like:

mol new 02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c.bgf
mol new 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c.bgf
mol new 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c.bgf
mol new 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c.bgf
mol new 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c.bgf

Further improvements:

with open("name.txt","r") as f:
    for i, line in enumerate(f):
        if i >= 225:
            break
        print("mol new %s.bgf"%(line.rstrip('\n')))

Notes:

  1. You want to use with open("name.txt","r") as f to assure that the file f gets closed regardless.

  2. Looping over i as a counter as in i=1; while(i<=225): i+=1 is not pythonic. Use enumerate instead.

  3. readline reads in a line. There is no need for splitlines.

  4. By looping over the lines in the file with for i, line in enumerate(f):, we eliminate the need to read the whole file in at once. This makes the program suitable for handling very large files.

  5. In python, when a line is read from a file, it still has the newline at the end of it. We use rstrip('\n') to safely remove it.

like image 157
John1024 Avatar answered Jan 15 '23 14:01

John1024


The readline function reads a single line from the file. Then you ask to split the line into a list of lines (which will give you a list of only one line since that's what you have).

Don't split the single line. Instead strip the string (to remove leading and trailing "white-space").

Please read the string reference for more information about both splitlines and strip.

like image 26
Some programmer dude Avatar answered Jan 15 '23 12:01

Some programmer dude