简体   繁体   English

将文件输入的标准输出保存到文件

[英]Save stdout of fileinput to file

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...抱歉,我对 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)

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?现在,输出是正确的,但我必须覆盖文件,我该怎么办?

Use inplace=True使用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)

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您可以将所有结果存储到一个列表中并迭代到该列表并使用“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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM