Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

avoid blank line when reading names from .txt into python list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading