Python Forum
Delete multiple files using file extention - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Delete multiple files using file extention (/thread-15565.html)



Delete multiple files using file extention - sumncguy - Jan-22-2019

I script in bash and some expect and I am trying to make the move to python.
I have taken a beginner class at a local community college and am now trying to put "it" to use.
The best way for me to do so is to look at what I have written in bash and expect and rewrite in python.


I am working at a Centos Linux VM command line
Python 2.6.6 (I know old and crusty)

So my question :
Quote:#!/usr/bin/python
import glob, os
for f in glob.glob("*.err"):
os.remove(f)

The snip of code works well to delete any file with an extension of ".err".
For instance, I want to be able to delete any file with an extension of .err and the extension of .log

The python equivalent to the Linux command line :
Quote:rm *.log *.err

Thanks in advance !!


RE: Delete multiple files using file extention - metulburr - Jan-22-2019

As far as i am aware i dont think there is a way to return multiple hits with glob.

use zip to iterate over both
for f1,f2 in zip(glob.glob('*.err'), glob.glob('*.log')):
    os.remove(f1)
    os.remove(f2)
or for a shorter for loop header
err = glob.glob('*.err')
log = glob.glob('*.log')

for f1,f2 in zip(err, log):
    os.remove(f1)
    os.remove(f2)
or just use a function
def remove_files(ext):
    for f in glob.glob(ext):
        os.remove(f)
        
remove_files('*.err')
remove_files('*.log')



RE: Delete multiple files using file extention - snippsat - Jan-23-2019

Can write own function with itertools chain() to make glob take unlimited arguments.
from glob import iglob
from itertools import chain
import os

def multi_glob(*args):
    return chain.from_iterable(iglob(pattern) for pattern in args)

for filename in multi_glob('*.txt', '*.bmp', '*jpg'):
         print(filename)
         #os.remove(filename)
Quote:The python equivalent to the Linux command line :
rm *.log *.err
So can make the same i call it py_rm,using my favorite command line tool Click.
# py_rm.py
from glob import iglob
from itertools import chain
import os
import click

def iter_glob(*args):
    return chain.from_iterable(iglob(pattern) for pattern in args)

@click.command()
@click.argument('arg', nargs=-1)
def rm(arg):
    for filename in iter_glob(*arg):
         click.echo(filename)
         #os.remove(filename)

if __name__ == '__main__':
    rm()
Test from command line.
Output:
C:\code\mod λ py_rm.py *.txt *.bmp *.jpg bar.txt spam.bmp test.bmp egg.jpg