user1934146
user1934146

Reputation: 3071

Removing images mentioned in a list

I am trying to construct a path for each image defined in images list and remove it if it exists,currently am hardcoding path for each image mentioned in imagelist below..is there an easier way to implement this?

import os
import subprocess
from subprocess import check_call,Popen, PIPE

def main ():
    images=['test1.img','test2.img','test3.img']
    ROOT="/local/mnt/workspace"
    target="wc3123"
    #Construct ROOT + "/out/target/product/" + target + "/test1.img 
    #for each image mentioned in imageslist remove if it exist"
    test1= ROOT + "out/target/product/" + target + "test1.ming"
    check_call("rm -rf %s" %test1,shell=True)

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 102

Answers (1)

Mattie B
Mattie B

Reputation: 21269

You can iterate over your images list of filenames like so:

def main ():
    images=['test1.img','test2.img','test3.img']
    ROOT="/local/mnt/workspace"
    target="wc3123"
    for image in images:
        #Construct ROOT + "/out/target/product/" + target + "/test1.img 
        #for each image mentioned in imageslist remove if it exist"
        test1= ROOT + "out/target/product/" + target + "/" + image
        check_call("rm -rf %s" %test1,shell=True)

I recommend a few other cleanups as well, such as using os.unlink to remove the files instead of constructing a string to be passed to the shell (which is unsafe), parameterizing your constants so they can be replaced, and using os.path.join instead of concatenating pathnames:

import os

def main(images, root='/local/mnt/workspace', target='wc3123'):
    for image in images:
        os.unlink(os.path.join(root, target, image))

if __name__ == '__main__':
    main(['test1.img', 'test2.img', 'test3.img'])

Upvotes: 3

Related Questions