我正在尝试为图像列表中定义的每个图像构建一个路径,如果它存在则将其删除,目前是下面图像列表中提到的每个图像的硬编码路径..是否有更简单的方法来实现它?
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()
答案 0 :(得分: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
删除文件而不是构造一个传递给shell的字符串(这是不安全的),参数化你的常量以便可以替换它们,并使用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'])