-2

I'm pretty new to python but I wrote this code to read a csv file, ping the list of ip address in the first column and output the status and IP address to another csv file using the csv writer function. Eventually I want to be able to write just the status to the new csv file because all the other data will not change. Can anyone help me do this? Essentially I need a way to only write to a specific column in TEST2.csv

import platform    # For getting the operating system name
import subprocess as sp  # For executing a shell command
import csv

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host 
    name is valid.
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '2', host]

    return sp.call(command) == 0

with open('TEST.csv') as rfile:
    reader = csv.reader(rfile)
    count = 0 
    status = 0
    strstatus = ''
    with open('TEST2.csv','w',newline='') as wfile:
        fieldnames = ['a','b','c','d','IP Address', 'Status']
        # a,b,c,d are placeholders for other other fieldnames in datafile
        writer = csv.DictWriter(wfile,fieldnames=fieldnames)
        next(reader)
        writer.writeheader()
        for IP in reader:
            status = ping(IP)
            if status:
                strstatus = 'Online'
            else:
                strstatus = 'Offline'
            writer.writerow({'a':None, 'b':None, 'c':None , 'd':None , 'IP Address' : 
IP,'Status' : strstatus})
            count += 1
            if count > 4:
                break
rfile.close()
wfile.close()

1 Answers1

0

Kind of a complete re-write using some of your code, but should do the job:

import platform
import subprocess as sp
import csv

INPUT_FILENAME = 'Input.csv'
INPUT_FIELDNAMES = ['column_1', 'column_2', 'ip']
INPUT_DELIMITER = ';'

OUTPUT_FILENAME = 'Output.csv'
OUTPUT_DELIMITER = ';'
OUTPUT_FIELDNAMES = ['column_1', 'column_2', 'ip', 'status']

NUMBER_OF_PINGS = 2
pings = str(NUMBER_OF_PINGS)


def ping(host, pings=pings):
    # https://stackoverflow.com/a/32684938/3991125
    param = '-n' if platform.system().lower() == 'windows' else '-c'
    command = ['ping', param, pings, host]
    print('Pinging {}'.format(host))
    is_available = sp.call(command, stdout=sp.DEVNULL, stderr=sp.DEVNULL) == 0
    print('--> available: {}'.format(is_available))
    return is_available


def read_csv(filepath, fieldnames, delimiter):
    with open(filepath) as input_file:
        reader = csv.DictReader(input_file, fieldnames=fieldnames, delimiter=delimiter)
        data = [row for row in reader]
    return data


def work(data):
    for d in data:
        ip = d.get('ip')
        is_available = ping(ip)
        d['status'] = is_available
    return data


def write_csv(data, filepath, fieldnames, delimiter):
    with open(filepath, 'w') as output_file:
        writer = csv.DictWriter(output_file, fieldnames=fieldnames, delimiter=delimiter)
        writer.writeheader()
        writer.writerows(data)


if __name__ == "__main__":
    data = read_csv(INPUT_FILENAME, INPUT_FIELDNAMES, INPUT_DELIMITER)
    processed = work(data)
    write_csv(processed, OUTPUT_FILENAME, OUTPUT_FIELDNAMES, OUTPUT_DELIMITER)
albert
  • 8,027
  • 10
  • 48
  • 84
  • Why use a semicolon as the delimiter, instead of a comma? – AMC Mar 12 '20 at 19:03
  • I am often working with datasets which contain `,` as decimal sign. To prevent any complications, I am using `;` as data delimiter by default as my 'personal best practice' / preferred workflow. – albert Mar 12 '20 at 20:35