python - 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?
解决方案
您可以使用glob
like(未经测试)删除这些文件:
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)
推荐阅读
- firebase - 从 Travis CI 部署到 Firebase 时出错
- mysql - 显示匹配对并返回
- python - 在 VS Code 中运行 Python 代码并且无法在同一文件夹中找到文件
- vue.js - Vee 验证:SyntaxError:无效的正则表达式
- python - 在嵌套字典中添加相同键的值
- amazon-web-services - 无法在正在运行的 EMR 上执行步骤
- python - 如何处理 Jupyter notebook (Anaconda) 上的内核错误?
- javascript - 屏幕锁定时隐藏移动浏览器视频内容
- ruby-on-rails - 如何用 ActiveSupport::LoggerSilence 替换 LoggerSilence?
- azure-devops - 在 azure devOps 中,如何在项目中复制仪表板