首页 > 解决方案 > iterate arrays in python and delete those file if it exists

问题描述

I have a Python script as shown below which reads four files and give the difference between those files for each clientId and it works fine:

#!/usr/bin/python
import os, sys, re, json

with open(sys.argv[1]) as old_primary, open(sys.argv[2]) as new_primary, \
    open(sys.argv[3]) as old_second, open(sys.argv[4]) as new_second:

    prepare_json = lambda f: json.loads(re.sub(r'([0-9]+)=', '"\\1":', f.read())) 
    old_pr_data = prepare_json(old_primary)
    new_pr_data = prepare_json(new_primary)
    old_snd_data = prepare_json(old_second)
    new_snd_data = prepare_json(new_second)

    k = sys.argv[5]
    print('ClientId ' + k)
    print('pri=({})'.format(' '.join(map(str, set(old_pr_data[k]) ^ set(new_pr_data[k])))))
    print('snd=({})\n'.format(' '.join(map(str, set(old_snd_data[k]) ^ set(new_snd_data[k])))))

Here is how I am running it:

python test.py old_primary_mapping.txt new_primary_mapping.txt old_secondary_mapping.txt new_secondary_mapping.txt 1

Problem Statement

This is the output I get for clientId 1 after running above script:

ClientId 1
pri=(192 196 176)
snd=(1482 1485 1491 1494)

Now I want to iterate pri and snd array and make a file string like as shown below and delete those files if it exists. I am having * regex in the file.

For pri, delete these files:

/primary/proc_192_for_*.log
/primary/proc_196_for_*.log
/primary/proc_176_for_*.log

For snd, delete these files:

/secondary/proc_1482_for_*.log
/secondary/proc_1485_for_*.log
/secondary/proc_1491_for_*.log
/secondary/proc_1494_for_*.log

I just need to make sure that I am deleting these files only what is there in pri and snd array. Is this possible to do in python?

标签: pythonfile-iodelete-file

解决方案


您可以使用globlike(未经测试)删除这些文件:

for dir_name, numbers in (('primary', pri), ('secondary', snd)):
    for number in numbers:
        for filename in glob.glob('/{}/proc_{}_for_*.log'.format(dir_name, number)):
             os.unlink(filename)

推荐阅读