I'm listing all files within a folder with os.listdir
and was wondering how I would run a loop to remove any folders, aka strings within that list that don't end with .exe, .jpg, and so on.
Asked
Active
Viewed 474 times
-2

Trenton McKinney
- 56,955
- 33
- 144
- 158
-
1Folders do not have .exe at end. you talking about removing files? – Ahmad Anis Jun 13 '20 at 17:47
-
5Use `os.path.isdir()` to check if a pathname is a directory or not. – G. Sliepen Jun 13 '20 at 17:47
-
1It's perilous to rely upon file extensions telling you if something is a folder or not. That's not very reliable, as you can have folders with extensions and files that don't have them. – Blckknght Jun 13 '20 at 17:47
2 Answers
1
I won't code the complete solution for you, but here are the components you need to get coding yourself.
os.listdir
to list the files (you already figured this out)os.path.isfile
in order to not delete directories that could have weird names with extensionsos.path.split
in order to get the extension of a fileos.remove
to remove a file.
(I'm assuming you want to remove files, not folders. If you really want to remove folders, use os.path.isdir
instead of os.path.isfile
.)

timgeb
- 76,762
- 20
- 123
- 145
-
-
@SayandipDutta I don't think it's needed. You already have the filename before you split, no need to join again. – timgeb Jun 13 '20 at 17:52
0
Let's say that your list is
>>> mylist
['hello.exe', 'abc.jpg', 'that', 'bro']
and you want to remove that
and bro
file because they do not have .jpg
and .exe
extension. So we use del
operator from Python.
This is the code:
>>> for i in range(len(mylist)):
... if not (".exe" in mylist[i] or ".jpg" in mylist[i]):
... del mylist[i]
... i = i-1
And now if we check mylist
output is
>>> mylist
['hello.exe', 'abc.jpg']
Generally to remove files from your computer, you have to use os.remove
. So you can try
location = "/home/User/Documents" #your path to in which you want to del file
for i in range(len(mylist)):
if not (".exe" in mylist[i] or ".jpg" in mylist[i]):
os.remove(mylist[i])
del mylist[i]
i = i-1

Ahmad Anis
- 2,322
- 4
- 25
- 54