是否可以将整个python输出写入文本或csv文件?

2024-06-16 08:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在研究traceroute,所以我想知道是否可以将整个python traceroute结果输出写入txt和Csv文件?我怎么能做到这一点呢?因为我找不到合适的方法来演示。你知道吗

谢谢


Tags: 文件csv方法txttraceroute新手
1条回答
网友
1楼 · 发布于 2024-06-16 08:23:30
import subprocess

with open("hostlist.txt", "r") as hostlist, open("results.txt", "a") as output:
    for host in hostlist:
        host = host.strip()

        print "Tracing", host

        trace = subprocess.Popen(["tracert", "-w", "100", host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        while True:
            hop = trace.stdout.readline()

            if not hop: break

            print ' >', hop.strip()
            output.write(hop)

        # When you pipe stdout, the doc recommends that you use .communicate()
        # instead of wait()
        # see: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
        trace.communicate()

我正在从主机列表中读取主机详细信息,并在文件中写入o/p

相关问题 更多 >