![](/img/trans.png)
[英]Iterating through directory for all csv files and creating kml for each individual(csv) file and save using file name
[英]Creating CSV file in python which will list all files from a directory with a server name alongside
我目前正在尝试弄清楚如何在python中创建CSV文件,该文件将列出/ logs类别中的所有文件以及服务器名称(通过SSH)。 问题是,每当我启动脚本时,都会得到类似以下内容的信息:
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”从logs文件夹获取所有文件,问题是我不知道如何将每个文件分别放入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的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.