0

I want print just the odd lines from text how can I do that? I wrote this code but it print just the first line f=open('12.txt',r) n=0 while True: if n<=6: n=n+1 if n%2==1: lines=f.readlines ( )[n] print lines else: break

15th Aug 2016, 10:43 PM
sola
sola - avatar
8 Réponses
+ 3
Well let's start with what went wrong with your original code. First thing I notice is that the loop breaks if n is not odd, meaning the loop only runs once. Instead you should have wrote continue in the else block. Second thing is your use of readlines. If you are familiar with the read function, you know that once you read to the specified position, it does not return to the beginning. It stays where it left off. Readlines acts the same way in that regard. Once readlines is called, unless the number of lines to read was specified, the read position will be at the end of the file, meaning any attempts to call readlines will give you an empty list. If you use seek(0) after readlines, the read position will return to the beginning and you could successfully call readlines again. However you really don't need to do this. If you store the value of readlines to a variable you do not need to call it again. With that in mind you now have many ways of accessing the odd lines of your text. e.g f=open("file.txt","r") lines=f.readlines() n=0 while n<=len(lines): print(lines[n]) n=n+2
16th Aug 2016, 3:01 PM
Gershon Fosu
Gershon Fosu - avatar
0
readlines() read all the file continent at once. Try to read the lines before the while loop, and print lines[n] inside
15th Aug 2016, 11:30 PM
‫Ido Tal
‫Ido Tal - avatar
0
I try it but it didn't work :(
15th Aug 2016, 11:54 PM
sola
sola - avatar
0
You can do it in another way f=open('12.txt',r) n=0 for line in f: n = n+1 if n%2==1: print line
16th Aug 2016, 12:02 AM
‫Ido Tal
‫Ido Tal - avatar
0
it says n is not defined and if I put n=0 nothing happen.
16th Aug 2016, 12:13 AM
sola
sola - avatar
0
that work, just change the first line f=[12,765,34,87,33] n=0 for line in f: n = n+1 if n%2==1: print(line)
16th Aug 2016, 12:24 AM
‫Ido Tal
‫Ido Tal - avatar
0
sorry I really tried it but it didn't work.
16th Aug 2016, 12:35 AM
sola
sola - avatar
0
Thanks
16th Aug 2016, 8:27 PM
sola
sola - avatar