DeveloperLV
DeveloperLV

Reputation: 1781

How not to show specific values from a directory using glob?

My Goal:

Current goal for me is to return values that don't contain the value test.docx

My Current code:

I have this code here:

    # Create a Tkinter variable
    self.tkvar = StringVar()

    # Directory
    self.directory = "C:/Users/label/Desktop/Sign off project/test only/to sign"
    self.choices = glob.glob(os.path.join(self.directory, "*")) #all choices

What it does:

That gives me all file names inside a specific folder. How can I add a condition not to return me values that end with "test.docx"

Would your answer depend on the following code?

I have this code here, it's a OptionMenu / drop down menu of values in tkinter.

I have added this in, as I believe the code may be slightly different when working with drop down menu's

self.popupMenu = OptionMenu(main, self.tkvar, *self.choices) # Dropdown menu of all files inside the folder

Upvotes: 0

Views: 61

Answers (2)

sturgemeister
sturgemeister

Reputation: 456

you can always filter the results of glob:

    # Create a Tkinter variable
    self.tkvar = StringVar()

    # Directory
    self.directory = "C:/Users/label/Desktop/Sign off project/test only/to sign"
    self.choices = glob.glob(os.path.join(self.directory, "*")) #all choices
    self.choices = list(filter(lambda x: not x.endswith("test.docx"), self.choices))

the filter returns a generator, so you might want to convert it to a list, depending on what you're doing with it.

edit: I saw that you are unpacking self.choices, this does require it to be a listlike

Upvotes: 1

Denver
Denver

Reputation: 639

You could try using list comprehension:

# Create a Tkinter variable
self.tkvar = StringVar()

# Directory
self.directory = "C:/Users/label/Desktop/Sign off project/test only/to sign"
self.choices = glob.glob(os.path.join(self.directory, "*")) #all choices
# list comprehension to filter 
self.choices = [f for f in self.choices if 'test.docx' not in f]

This would remove any elements from self.choices that contain 'test.docx'

Upvotes: 1

Related Questions