daniel_e
daniel_e

Reputation: 257

Reading txt results 0, but has entries

strange problem and I can't find the issue. The following code copies filtered entries into a new txt and should print the number of entries, that the only_iphone.txt file contains (in lines) in the end.

The result is always 0. When I open the txt, however, it contains entries.

Am I missing something?

term = "iphone"
file = open(./export/importlist.txt')
extoutput = open('./export/only_iphone.txt', 'w')
for line in file:
    line.strip().split(',')
    if term in line and 'samsung' not in line and 'htc' not in line:
        #print line
        extoutput.write('{}'.format(line))
file.close()
time.sleep(1)


numberofentries = 0

with open('./export/only_iphone.txt') as f:
    for line in f:
        if line.strip():
            numberofentries += 1

    print (numberofentries)

Upvotes: 1

Views: 53

Answers (2)

Chuk Ultima
Chuk Ultima

Reputation: 1037

To continue on Gabriel's answer, it's better practice to use the with open way of opening a file. so you cannot forget to close it, like you did in the second part of your code.

term = "iphone"
with open('./export/importlist.txt') as my_file:
    with open('./export/only_iphone.txt', 'w') as extoutput:
        for line in my_file:
            line = line.strip().split(',')
            if term in line and 'samsung' not in line and 'htc' not in line:
                #print line
                extoutput.write('{}'.format(line))

time.sleep(1)


numberofentries = 0

with open('./export/only_iphone.txt') as f:
    for line in f:
        if line.strip():
            numberofentries += 1

    print (numberofentries)

Upvotes: 1

Gabriel B.R
Gabriel B.R

Reputation: 278

You forgot to close your extoutput file

term = "iphone"
file = open('./export/importlist.txt')
extoutput = open('./export/only_iphone.txt', 'w')
for line in file:
    line = line.strip().split(',')
    if term in line and 'samsung' not in line and 'htc' not in line:
        #print line
        extoutput.write('{}'.format(line))
file.close()
extoutput.close()

time.sleep(1)


numberofentries = 0

with open('./export/only_iphone.txt') as f:
    for line in f:
        if line.strip():
            numberofentries += 1

    print (numberofentries)

Upvotes: 2

Related Questions