1

sorry but i'm very new to python, i need a script to search by pattern and replace entire line into a file, i have insert entire script but the problem is after 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)

The output is:

AWS_ACCESS_KEY="xxxxxxx"
AWS_SECRET_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxx"

Now, output is correct, butI have to overwrite the file, how can I do?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
stecog
  • 2,202
  • 4
  • 30
  • 50

2 Answers2

1

Use 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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can store all of your result into one list and iterate over to that list and write into the file using "with statement" as shown below

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)
devender
  • 90
  • 8