Zion Oyemade
Zion Oyemade

Reputation: 433

How do I delete a specified number of files in a directory in Python?

I want to reduce the number of files in a folder or rather remove a specified number of files from the folder. I'd appreciate simple solutions likely limited around my code below, which definitely is not working and wrong.

files = os.listdir()
for file in files:
    for file in range(11):
        os.remove(file)

Upvotes: 5

Views: 7881

Answers (3)

Zion Oyemade
Zion Oyemade

Reputation: 433

Thanks everyone, I also did a bit of digging and applying solutions from your contributions. Here is what I got. The sorting was via creation time which was more logical for the task.

import os
import re

filepath = os.getcwd()
files = os.listdir(filepath)
files = sorted(files,key=os.path.getmtime)
for file in files[:11]:
    os.remove(file)

Upvotes: 1

Gsk
Gsk

Reputation: 2955

You simply have to iterate correctly in the range:

files = os.listdir('path/to/your/folder')
for file in files[:11]:
    os.remove(file)

in this way you are iterating through a list containing the first 11 files.

If you want to remove random files, you can use:

from random import sample

files = os.listdir('path/to/your/folder')
for file in sample(files,11):
    os.remove(file)

Upvotes: 4

MD5
MD5

Reputation: 1786

import os

files = os.listdir(r'C:/testdeletefolder')
fileslist=[]
for file in files:
    print file
    fileslist.append(file)

for i in range(0,2):
    os.remove(fileslist[i])

But ensure that you if condition to not to delete the python file which has code.this will delete 2 files you can change the counter in range

Upvotes: -1

Related Questions