我目前正在尝试弄清楚如何在 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/