I'm trying read a list of names from a .txt file into python so I can work with it.
humans = ['Barry', 'Finn', 'John', 'Jacob', '', 'George', 'Ringo', '']
with open(p_to_folder / 'humans.txt', 'w') as f:#using pathlib for my paths
for h in humans:
f.write(f'{h}\n')
What I'd like to do is read the .txt file back in so that I can work with names again, but leave out the blanks.
I have tried
with open(p_to_folder / 'humans.txt', 'r') as f:#using pathlib for my paths
new_humans = [line.rstrip() for line in f.readlines() if line != '']
when I inspect this is list I get
['Barry', 'Finn', 'John', 'Jacob', '', 'George', 'Ringo', '']
I can just run the line
new_humans = [i for i in new_humans if i != '']
and get
['Barry', 'Finn', 'John', 'Jacob', 'George', 'Ringo']
but I'd like to be able to do it in one line, and also to understand why my if statement isn't working in the original list comprehension.
Thank you
CodePudding user response:
Try this.
with open(p_to_folder / 'humans.txt', 'r ') as f:#using pathlib for my paths
new_humans = [line.rstrip() for line in f.readlines() if line.strip()]
CodePudding user response:
You can do sth like this:
with open(p_to_folder / 'humans.txt', 'r') as f:
new_humans = [line for line in f.read().splitlines() if line]
Or:
with open(p_to_folder / 'humans.txt', 'r') as f:#using pathlib for my paths
new_humans = [line.strip() for line in f.readlines() if line != '\n']
Output:
['Barry', 'Finn', 'John', 'Jacob', 'George', 'Ringo']