IAMrelentless
IAMrelentless

Reputation: 11

PYTHON Why does this for loop print every other line

f=open('l.txt','r')

for line in f:
    f_list=f.readline().split(",")
    if f_list[5]=="":
        print(f_list)

The file is a list and the 5th element is either "Y" or Blank, this loop is only printing every-other line. Why is it skipping them?Thanks.

The file is in this format ,but there's a few hundred more im trying to see if f[5] is Y or blank

#1,00/00/00,00:00,name,string,Y,string
#2,23/03/17,13:00,gfdfh,fdsdf,,kyl

Upvotes: 0

Views: 1577

Answers (2)

Joseph Chotard
Joseph Chotard

Reputation: 695

The answer is very simple: on every other line, the 6th element of the list is empty!

If you add a little line of code to help debug:

f=open('l.txt','r')

for line in f:
    f_list=f.readline().split(",")
    print(f_list[5])
    if f_list[5]=="":
        print(f_list)

The output is:

Y

['#2', '23/03/17', '13:00', 'gfdfh', 'fdsdf', '', 'kyl']

Your code checks if the 6th element of the list is equal to: "" (empty String). If the 6th element of the list is empty it prints out the list, if it isn't it doesn't print out the list.

In this case, the first line's six element is not empty so the list doesn't get printed.

To fix it, simply do the following:

f=open('l.txt','r')

for line in f:
    f_list=f.readline().split(",")
    if f_list[5]=="" or f_list[5]=="Y":
        print(f_list)

You forgot to check if it's equal to Y!

Upvotes: 1

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

For every line in file

f=open('N:\CA Folder\\firesideFixtures.txt','r')

for f_list in f.read().splitlines():
    f_list=f_list.split(",")
    if f_list[5]=="":
        print(f_list)

Output:

['2', '23/03/17', '13:00', 'gfdfh', 'fdsdf', '', 'kyl']

Suggestion:

readline() get the \n along with the line that is read.

Example,

my textfile.txt is:

hello this is testing
test line 2

testline3

Here when you read,

f = open('textfile.txt','r') 

print f.readlines():
['hello this is testing\n', 'test line 2\n', '\n', 'testline3\n']

Therefore, you can use

print f.read().splitlines()

which will give

['hello this is testing', 'test line 2', '', 'testline3']      

Hope this helps!

Upvotes: 0

Related Questions