Dennis Skov Hermannsen Dennis Skov Hermannsen - 2 months ago 17
Python Question

Exclude certain directories in Python3

I've been porting (very simply) a Python script from Windows to Linux (directory changes mostly), and I want to add a few new features to it.
The script is used to update mods on a game server. All mods are located in ShooterGame/Content/Mods/. Some mods are included by default (TheCenter and 11111111) - every other mod is located in the same folder as the default ones, but the names consist of random numbers.

I've been trying to exclude the 2 default directories and then build a list of contents of the ShooterGame/Content/Mods/ folder, but I've failed to do so.
This is the code that I've tried to use to exclude just the TheCenter folder:

def build_list_of_mods(self):
Build a list of all installed mods by grabbing all directory names from the mod folder
exclude = ["TheCenter"]
if not os.path.isdir(os.path.join(self.working_dir, "ShooterGame/Content/Mods/")):
for curdir, dirs, files in os.walk(os.path.join(self.working_dir, "ShooterGame/Content/Mods/")):
for d in dirs:
dirs[:] = [d for d in dirs if d not in exclude]

It doesn't work, sadly. Have I missed something or just done everything wrong?


I'm assuming you want self.installed_mods to contain the values of dirs without the values of exclude. You could simply call dirs.remove() with the values of exclude and then append the content of dirs to self.installed_mods. Or in a shorter way: self.installed_mods.extend([dir for dir in dirs if dir not in exclude]).