I wanted to ask the forum how can I delete multiple files in a folder using Python. I tried using the import os module along with os.unlink()
module, but it doesn't work. Any help would be greatly appreciated.
Asked
Active
Viewed 1,741 times
-4
-
Repeated use of `os.unlink` should be a suitable means of removing multiple files. If your code did not work, please post a [mcve] and a precise description of what actually happened when you ran it. If you got an error message, post that too, including stack trace. – user2357112 May 04 '18 at 17:10
-
What does "it doesn't work" mean? If you need help fixing your code, you have to post a [mcve]. Or if you _aren't_ asking for help debugging your code, then I'm afraid this is a duplicate, because "how do I delete files" has been asked innumerable times in the past. – Aran-Fey May 04 '18 at 17:10
-
Seems to be a similar question,Please check https://stackoverflow.com/questions/185936/how-to-delete-the-contents-of-a-folder-in-python – BARATH May 04 '18 at 17:11
-
import os for filename in os.listdir('c:\\users\\user1\\Pictures'): if filename.endswith('.txt'): os.unlink(filename) – Datalink May 04 '18 at 17:38
-
And this is the error I get: Traceback (most recent call last): File "C:/Users/user1/Documents/My Scripts/delete2.py", line 4, in
os.unlink(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'New Text Document.txt' – Datalink May 04 '18 at 17:40
1 Answers
0
Most likely it's because the filename used in the os.unlink(filename) isn't a full path to the file (os.listdir() just returns a sequence of filenames). You probably need to use os.path.join()
to prefix the 'c:\\users\\user1'
folder to it first.
Something along these lines:
import os
folder = 'c:\\users\\user1\\Pictures'
for filename in os.listdir(folder):
if filename.endswith('.txt'):
os.unlink(os.path.join(folder, filename))

martineau
- 119,623
- 25
- 170
- 301