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
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:
You want to use with open("name.txt","r") as f
to assure that the file f
gets closed regardless.
Looping over i
as a counter as in i=1; while(i<=225): i+=1
is not pythonic. Use enumerate instead.
readline
reads in a line. There is no need for splitlines
.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With