AugustoQ
AugustoQ

Reputation: 507

Python not ignoring empty items in list

I have this code to print some strings to a text file, but I need python to ignore every empty items, so it doesn't print empty lines.
I wrote this code, which is simple, but should do the trick:

lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
    if category.split(",")[0] is not "" and category is not None:
        lastReadCategories.write(category + '\n')
        print(category)
    else: print("/" + category + "/")
lastReadCategories.close()

I can see no problem with it, yet, python keeps printing the empty items to the file. All categories are written in this notation: "category,timesRead", that's why I ask python to see if the first string before the comma is not empty. Then I see if the whole item is not empty (is not None). In theory I guess it should work, right?
P.S.: I've already tried asking the if to check if 'category' is not "" and is not " ", still, the same result.

Upvotes: 3

Views: 1826

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121148

Test for boolean truth instead, and reverse your test so that you are certain that .split() will work in the first place, None.split() would throw an exception:

if category is not None and category.split(",")[0]:

The empty string is 'false-y', there is no need to test it against anything.

You could even just test for:

if category and not category.startswith(','):

for the same end result.

From comments, it appears you have newlines cluttering up your data. Strip those away when testing:

for category in lastReadCategoriesList:
    category = category.rstrip('\n')
    if category and not category.startswith(','):
        lastReadCategories.write(category + '\n')
        print(category)
    else: print("/{}/".format(category))

Note that you can simply alter category inside the loop; this avoids having to call .rstrip() multiple times.

Upvotes: 4

PSS
PSS

Reputation: 6101

rstrip() your category before writing it back to file

lastReadCategories = open('c:/digitalLibrary/' + connectedUser +'/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
    lastReadCategories.write(category.rstrip() + '\n')
    print(category.rstrip())
else: print("/" + category + "/")
lastReadCategories.close()

I was able to test it with your sample list provided (without writing it to file):

lastReadCategoriesList =  ['A,52', 'B,1\n', 'C,50', ',3']
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
    print(category.rstrip())
else: print("/" + category + "/")

>>> ================================ RESTART ================================
>>> 
A,52
B,1
C,50
/,3/
>>> 

Upvotes: 1

dawg
dawg

Reputation: 103694

The classic way to test for an empty string (ie, only whitespace but not '') is with str.strip():

>>> st='   '
>>> bool(st)
True
>>> bool(st.strip())
False

Which also works on a null string:

>>> bool(''.strip())
False

You have if category.split(",")[0] is not "" ... and this is not the recommended way. You can do this:

if category.split(',')[0] and ...

Or, if you want to be wordier:

if bool(category.split(',')[0]) is not False and ...

And you may be dealing with an issue with leading whitespace in the CSV:

>>> '    ,'.split(',')
['    ', '']
>>> '     ,val'.split(',')
['     ', 'val'] 

Upvotes: 0

Related Questions