0

I am trying to delete all files from a directory apart from two (which will be erased, then re-written). One of these files, not to be deleted, contains the names of all files in the folder/directory (the other contains the number of files in the directory).

I believe there (possibly?) are 2 solutions:

Read the names of each file from the un-deleted file and delete them individually until there is only the final 2 files remaining,

or...

Because all other files end in .txt I could use some sort of filter which would only delete files with this ending.

Which of these 2 would be most efficient and how could it be done? Any help would be appreciated.

1 Answer 1

1

You are going to end up deleting files one by one, regardless of which method you use. Any optimizations you make are going to be very miniscule. Without actually timing your algorithms, I'd say they'd both take about the same amount of time (and this would vary from one computer to the next, based on CPU speed, HDD type, etc). So, instead of debating that, I'll provide you code for both the ways you've mentioned:

Method1:

import os def deleteAll(infilepath): with open(infilepath) as infile: for line in infile: os.remove(line) 

Method 2:

import os def deleteAll(): blacklist = set(['names/of/files/to/be/deleted', 'number/of/files']) for fname in (f for f in os.listdir() if f not in blacklist): os.remove(fname) 
Sign up to request clarification or add additional context in comments.

3 Comments

What are the 2 different file paths in method 1? Would one be the folder containing all files and the other the file containing the filenames?
There is only one path mentioned there - the path to the file containing the paths to the files to be deleted
Ok, I'll have a little play around with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.