1

我正在尝试为图像列表中定义的每个图像构建一个路径,如果存在则将其删除,目前是下面图像列表中提到的每个图像的硬编码路径..有没有更简单的方法来实现这个?

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()
4

1 回答 1

3

您可以像这样遍历images文件名列表:

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)

我还建议进行一些其他清理,例如使用os.unlink删除文件而不是构造要传递给外壳的字符串(这是不安全的),参数化常量以便可以替换它们,以及使用os.path.join而不是连接路径名:

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'])
于 2013-01-02T17:25:36.893 回答