Joe Smart
Joe Smart

Reputation: 763

Removing certain files specified in a list

I am going to be using datetime library to create a list of dates that are considered "valid". A valid date is a date that is

a) A working Day

b) Less than 14 working days old.

The dates are in format 20140917 - %Y%m%d

I then intend to iterate over a list of files and if the file name (which is in identical format) is not in this list, then delete the file.

However I know that deleting anything from the list you're iterating over is bad.

How would I go about this then, because I must iterate over the list of files and my pure intention is to delete some of them.

As a side note, I am also struggling on creating the list of valid dates.

I currently have this snippet from a previous script I wrote, but I can't work out how to use it to create a list of "valid" dates.

for (day,name) in itertools.izip((day for day in (datetime.today()+timedelta(n) for n in xrange(20)) if day.weekday() not in (5,6)), (itertools.cycle(names))):

Upvotes: 1

Views: 88

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55469

I think there might be some confusion here, Joe.

If you are iterating through a list of strings that are filenames, yes it's bad to delete a string from the list. But it's perfectly safe to delete the named file from your hard drive. Assuming (of course) that the list does, in fact, contain files that you may want to delete. :)

Upvotes: 1

zinjaai
zinjaai

Reputation: 2385

If i understand your question correctly you have a list with lots of dates. From this list you want to filter all dates that are older than 14 days and are not a week day.

This can be archieved by using the set and & command:

list_of_dates = ['0000000', '20140930', '11111111', '20140926', '20140925', '33333333']

# Create valid dates
now = datetime.now()
valid_days = [(now - timedelta(days=i)).strftime('%Y%m%d') for i in range(-14, 0) if (now-timedelta(days=i)).weekday() not in (5,6)]
# filter list
filtered = list(set(list_of_dates) & set(valid_days))

This results in the list:

'20140926', '20140930', '20140925'

Upvotes: 2

Hrabal
Hrabal

Reputation: 2525

To delete things from a list you are iterating in you can do something using this structure:

list_of_files[:] = [file for file in list if not in dates_list]

To make the code more readable and add extra checks you can sobstitute not in dates_list with a function call:

def file_check(file, dates_list):
  if conditionyoulike:
    return true
  else:
    return false

list_of_files[:] = [file for file in list if file_check(file,dates_list)]

Upvotes: 0

Related Questions