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