简体   繁体   中英

Creating CSV file in python which will list all files from a directory with a server name alongside

I am currently trying to figure out how to create a CSV file in python, which will list all files from /logs category alongside with server name by SSH. The problem is, whenever I start my script,I get something like:

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

When in my CSV I need something like this:

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

With my current code i am not sure how to start with this problem The relevant fragment looks like this:

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()

and as you can see... "r" gets all files from logs folder, the problem is I don't have any idea how to put each file separately to csv.

Use python in-build library 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()

Read more about Python csv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM