对不起,但是我是python的新手,我需要一个脚本来按模式搜索并将整行替换为文件,我已经插入了整个脚本,但是问题出在with fileinput...
#!/usr/bin/env python3
import json
import requests
import sys
import fileinput
url = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/test'
r = requests.get(url)
accesskey = json.loads(r.content.decode('utf-8'))['AccessKeyId']
secretkey = json.loads(r.content.decode('utf-8'))['SecretAccessKey']
with fileinput.input(files=('./envFile.sh')) as envfile:
for line in envfile:
if line.strip().startswith('export AWS_ACCESS_KEY='):
line = 'AWS_ACCESS_KEY="%s"\n' % (accesskey)
if line.strip().startswith('export AWS_SECRET_KEY='):
line = 'AWS_SECRET_KEY="%s"\n' % (secretkey)
sys.stdout.write(line)
输出为:
AWS_ACCESS_KEY="xxxxxxx"
AWS_SECRET_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxx"
现在,输出正确,但是我必须覆盖文件,该怎么办?
答案 0 :(得分:1)
使用inplace=True
例如:
import fileinput
with fileinput.input(files='./envFile.sh', inplace=True) as envfile:
for line in envfile:
if line.strip().startswith('export AWS_ACCESS_KEY='):
print(line.replace(line.strip(), 'AWS_ACCESS_KEY="%s"' % (accesskey)))
elif line.strip().startswith('export AWS_SECRET_KEY='):
print(line.replace(line.strip(), 'AWS_SECRET_KEY="%s"' % (secretkey)))
else:
print(line)
答案 1 :(得分:0)
您可以将所有结果存储到一个列表中,然后遍历该列表并使用“ with语句”将其写入文件 如下图所示
temp='AWS_ACCESS_KEY="{}"\n'.format(accesskey)
a.append(temp)
temp='AWS_SECRET_KEY="{}"\n'.format(secretkey)
a.append(temp)
with open(file_name,'w') as stream:
for i in a:
stream.write(i)