Я довольно новичок в python, но я написал этот код, чтобы прочитать файл CSV, пинговать список IP-адресов в первом столбце и выводить статус и IP-адрес в другой файл CSV, используя функцию записи CSV. В конце концов я хочу иметь возможность записать только статус в новый CSV-файл, потому что все остальные данные не изменятся. Может ли кто-нибудь помочь мне сделать это? По сути, мне нужен способ записи только в указанный столбец c в 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()