如何在Python中将输出保存为csv文件

问题描述 投票:0回答:1

我使用这个Python片段来获取rabbitmq队列大小输出,它已经是csv格式,但是我需要知道如何将此数据保存到文件中。

import subprocess

proc = subprocess.Popen("/usr/sbin/rabbitmqctl list_queues --formatter csv", shell=True, stdout=subprocess.PIPE)
stdout_value = proc.communicate()[0]
print stdout_value

我从这个片段中得到的输出

"name","messages"
"search_publish_queue","1"
.
.

我尝试使用

with open
将输出写入 csv 文件,但它会在每个字符旁边添加 , 。

import subprocess
import csv

with open('test.csv', 'w', ) as f:
    writer = csv.writer(f)
    proc = subprocess.Popen("/usr/sbin/rabbitmqctl list_queues --formatter csv", shell=True, stdout=subprocess.PIPE)
    stdout_value = proc.communicate()[0]
    writer.writerow(stdout_value)

它写入文件如下

",n,a,m,e,",",m,e,s,s,a,g,e,s,"
",s,e,a,r,c,h,_,p,u,b,l,i,s,h,_,q,u,e,u,e,",,,",1,"

执行此操作的编写方式是什么?如果不使用

python rabbitmq python-2.x rabbitmqctl
1个回答
0
投票

这是一个固定代码:

import subprocess
import csv

with open('test.csv', 'w', newline='') as f:  # Use 'newline' parameter to avoid extra newline characters
    writer = csv.writer(f)
    proc = subprocess.Popen("/usr/sbin/rabbitmqctl list_queues --formatter csv", shell=True, stdout=subprocess.PIPE)
    stdout_value = proc.communicate()[0].decode('utf-8')  # Decode the byte string to a regular string
    lines = stdout_value.strip().split('\n')  # Split the string into lines

    # Write each line as a CSV row
    for line in lines:
        writer.writerow(line.split(','))
© www.soinside.com 2019 - 2024. All rights reserved.