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.
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.
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