Python 将fileinput的标准输出保存到文件
很抱歉,我对python非常陌生,我需要一个脚本来按模式搜索并将整行替换到文件中,我已经插入了整个脚本,但问题是在使用fileinput后出现了Python 将fileinput的标准输出保存到文件,python,python-3.x,Python,Python 3.x,很抱歉,我对python非常陌生,我需要一个脚本来按模式搜索并将整行替换到文件中,我已经插入了整个脚本,但问题是在使用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
。
#!/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"
现在,输出是正确的,但我必须覆盖文件,我该怎么做?您可以将所有结果存储到一个列表中,然后迭代到该列表,并使用“with statement”写入文件 如下图所示
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)
使用
inplace=True
Ex:
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)
要覆盖该文件,您需要使用open(myfile,'w')以写模式打开该文件。您可以查看此答案