-3

In python, I need to redirect the o/p of the list to a file. I have the configuration file in json format (test_conf), which i am reading and adding the required commands. At the end, i need to create a file and redirect the output there. Please suggest how can i redirect the o/p at the end to a file ? Here is the snippet of the code :

#!/usr/bin/env python


import sys
import re
import time
import json


####### Reading json test_conf ###########
with open('test_conf') as file:
  data = json.load(file)
cert = data["cert"]
key = data["key"]

service_config = []
priority = 100

service_config.append('add patset api_auth_ps')
service_config.append('add patset api_unauth_ps')
service_config.append('add patset api_unauth_filetypes_ps')
service_config.append('add ssl certkey api_cert -cert '+cert+' -key '+key)
######## set of configuration here ###########

### Now, i need to redirect the o/p of the created service_config list to a file. 
######## Opening file to apply the config ######
sys.stdout = open('output.text', 'w')

for i in service_config :
        ### How can I add the content to the output.text ?? 
        
Pooja
  • 481
  • 1
  • 8
  • 15

1 Answers1

1

Something like this should work. Over here, we are adding each list item in each line of the text file, we can obviously change the format of the output according to our requirements.

my_list=[1,2,3,4]
with open('sample.txt', 'w') as f:
    for item in my_list:
        f.write(str(item)+"\n")
mozilla-firefox
  • 864
  • 1
  • 15
  • 23