Search code examples
pythonpython-3.xlistlist-comprehension

How can I filter out a List from a .txt file using list comprehension?


I am taking a Python class and I can't figure out a take home quiz. I am using IDLE to write the code.

We have to load a file called names.txt into a list. The file contains the following:

Joe Smith
000000
Jeff Mitchell
xxxxxxx
Benjamin Grant
12346

I need to filter out lines that contain the "xxxxxxx" or numbers. I am attempting to use list comprehension with the following code:

> names = open(r'C:\Users\abcdse\Documents\Python\names1.txt','r')
> names_contents = names.read()
> filtered_names = [n for n in names_contents if n !='xxxxxxx']
> names.close()
> print(filtered_names)

However, when I print the filtered_names output, names are not being filtered and rather than appearing in a dropdown format, they appear like this:

['J', 'o', 'e', ' ', 'S', 'm', 'i', 't', 'h', '\n', '0', '0', '0', '0', '0', '0', '\n', 'J', 'e', 'f', 'f', ' ', 'M', 'i', 't', 'c', 'h', 'e', 'l', 'l', '\n', 'x', 'x', 'x', 'x', 'x', 'x', 'x', '\n', 'B', 'e', 'n', 'j', 'a', 'm', 'i', 'n', ' ', 'G', 'r', 'a', 'n', 't', '\n', '1', '2', '3', '4', '6', '\n']

What am I doing wrong here? Is it possible to filter out both, the "xxxxxxx" and numbers?

Thank you for your support as I get started with code.


Solution

  • You were almost there

    names = open(r'C:\Users\abcdsed\Documents\Python\names1.txt','r')
    name_contents = names.readlines()  # list of lines
    filtered_names = [n for n in name_contents if (not n.isnumeric() or n != 'xxxxxxx']
    

    Might want to look things up using your favorite search engine before posting here though. This is a very trivial question.