Readline () returns a bracket

I wrote some codes to get some lines from .txt, as shown below, and save the return lines with brackets that I did not expect. 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 he 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
+4
source share
4 answers

You do not need to call the splitlines () method on readline () results

file.readline () returns one line of the file, including the ending new line.

.splitlines () gets rid of the new line, using it as a separator and providing you with a list of lines with only one element. The brackets are taken from the str representation of this 1st list.

Do you want to:

x = f.readline().rstrip()

to delete a new line, or you can also cut the new line as follows

x = f.readline()[:-1]

, , - , . Python

for line in fileobject:
    print line[:-1]

while .readline()

+1

, :

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()

, :

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

:

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')))

:

  • with open("name.txt","r") as f, , f .

  • i , i=1; while(i<=225): i+=1, . .

  • readline . splitlines.

  • for i, line in enumerate(f):, . .

  • python, , - . rstrip('\n') .

+4

readline . ( , ).

. ( " " ).

splitlines strip.

+3

, f.readline().splitlines() , .

:

x = f.readline().splitlines()
x = x[0]
+1
source

Source: https://habr.com/ru/post/1649975/


All Articles