I'm really new to Python, only working on it, as another guy in my team left and need to get some work over the line, so apologies if this is a stupid question.
I need to remove items from a list (they'll contain a certain phrase) and have googled and tried a few ways but it doesn't seem to be working.
What I've currently got is,
def get_and_count_card_files(date):
# Retrieve the DC and SD card files
dc_files = dc_card_files.get_dc_files(dc_start_location, date)
sd_files = sd_card_files.get_sd_files(sd_start_location)
print(dc_files)
if '*NoCover*' in dc_files:
dc_files.remove('*NoCover*')
Dc_files being the list (bunch of file names) and I need to remove anything that has NoCover in the file name. It does exist as the print function shows me it does.
Anyone any idea what I'm doing wrong
With this piece of code, the *
won't do a glob or regular expression in these contexts:
if '*NoCover*' in dc_files:
dc_files.remove('*NoCover*')
so it would be better to say:
if 'NoCover' in dc_files:
However, we then have to find the right entry to remove in the list, without using wildcards.
For a small list, you could iterate over it. A list comprehension would do:
new_dc_files = [dc for dc in dc_files if 'NoCover' not in dc]
It's a compact way of saying:
new_dc_files = list()
for dc in dc_files:
if 'NoCover' in dc:
continue
new_dc_files.append(dc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With