python - 在 python 中创建 CSV 文件,它将列出目录中带有服务器名称的所有文件

标签 python linux csv server ip

我目前正在尝试弄清楚如何在 python 中创建 CSV 文件,它将通过 SSH 列出/logs 类别中的所有文件以及服务器名称。 问题是,每当我启动我的脚本时,我都会得到类似的东西:

server, machine
IP;file1 file2, file3 file4 etc
IP2;file1 file2, file3, file 4 etc.

在我的 CSV 中,我需要这样的东西:

server, machine
IP;file1
IP;file2
Ip;file3
IP;file4
IP2;file1
IP2;file2
IP2;file3
etc...

使用我当前的代码,我不确定如何开始解决这个问题 相关片段如下所示:

SLIST = path to csv from which i took IP
CMD2 = 'ssh %s ls  /opt/syslog/logs'

def mloop():
     f = open('out.csv', 'a')
     columnTitleRow = "server, machine\n"
     f.write(columnTitleRow)

     for i in csv2hash(SLIST):


       if i.get('IP'):
          r = getoutput(CMD2 % (i['IP']))

       server = i['IP']
       machine = r
       row = server + ";" + machine + ";" + "\n"
       f.write(row)
     f.close()

如您所见...“r”从日志文件夹中获取所有文件,问题是我不知道如何将每个文件分别放入 csv。

最佳答案

使用 python 内置库 csv

import csv

output_file = open('outputfile.csv', 'wb')
fieldnames = ['server', 'machine']
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
writer.writeheader()

def mloop():
    ...
    ...
    server = i['IP']
    machine = r
    row = {'server': server, 'machine': machine}
    writer.writerow(row)

output_file.close()

阅读更多关于 Python csv 的信息

关于python - 在 python 中创建 CSV 文件,它将列出目录中带有服务器名称的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198172/

相关文章:

python - 是否可以在 python 3.7 中使用自记录 f 字符串?

python - Pandas 删除字符后一列中的所有字符串

linux - Windows 操作系统使用哪种语言进行编码?

python - 如何使用 csv.DictReader 跳过前标题行?

python - 获取外部对象Python的类型

python - Plotly:如何使用 DASH 回调将多项式拟合线添加到 plotly go.scatter 图形?

python - 如何从文本文件中读取逗号分隔值,然后将结果输出到文本文件?

使用 Jackson 读取 csv 时的 Java 过滤器值

linux - Qt5 linux如何设置窗口图标图片

linux - 用expect传递环境变量