簡體   English   中英

將 output 重定向到 python 中的文件

[英]Redirect the output to a file in python

在 python 中,我需要將列表的 o/p 重定向到文件。 我有 json 格式(test_conf)的配置文件,我正在讀取並添加所需的命令。 最后,我需要創建一個文件並將 output 重定向到那里。 請建議我如何將末尾的 o/p 重定向到文件? 這是代碼片段:

#!/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 ?? 
        

像這樣的東西應該工作。 在這里,我們在文本文件的每一行中添加每個列表項,我們顯然可以根據我們的要求更改 output 的格式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM