0

I am working on a search-and-destroy type program which I need it to do is search all directories with a certain file-name and append them to a list. after that delete all those files...not objects in list or the list...

    import os
file_list=[]
for root, dirs, files in os.walk(path-to-dir'):
       for f_name in files:
              if f_name.startswith("file-name"):
                     file_list.append(f_name)

I could write up to appending part of the code but I don't know next...

Some help please

2 Answers 2

1

To remove a file from your computer, use os.remove(). It takes full path to the file as it's parameter, so instead of calling os.remove("infectedFile.dll") you would call os.remove("C:/program files/avira/infectedFile.dll")

So your file_list should contain full paths to the files, and then just call:

for file in file_list:
    os.remove(file)
1
  • The full path must be added in the time of insertion into the file_list. It cannot be determined later.
    – pepr
    Dec 7, 2012 at 12:24
0

Modify your file_list.append(f_name). The f_name is only a bare name. You need to add the path to the file name in the time of processing, because you do not know where the file was found in the directory hierarchy:

        file_list.append(os.path.join(root, f_name))

The root variable contains the path during walking.

To make check whether your code works, just print the content of the list:

print('\n'.join(file_list))

Or you can do it in the loop to get ready for the later part:

for fname in file_list:
    print(fname)

Then you just add the os.remove(fname) to remove the file name:

for fname in file_list:
    print('removing', fname)
    os.remove(fname)
4
  • For the one who downvoted... Can you explain your objection? :)
    – pepr
    Dec 7, 2012 at 13:43
  • Wasn't me downvoting, but what exactly does this add to my answer?
    – user1632861
    Dec 7, 2012 at 13:47
  • @Mahi: I did not tell you downvoted, and I did not expected it either. Surya Teja Karra is probably a beginner. My answer shows how to add the full path you mention. The root changes during walking. This way, it must be added when the item is inserted to the list. This is what your answer does not show.
    – pepr
    Dec 7, 2012 at 14:06
  • But I do mention it. It leaves him something to figure out on his own, this site is not supposed to code programs for beginners, but to help them code it themselves.
    – user1632861
    Dec 7, 2012 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.