我对python非常陌生,但我编写这段代码是为了读取csv文件,ping第一列中的ip地址列表,并使用csv writer函数将状态和ip地址输出到另一个csv文件。最终,我希望能够将状态写入新的csv文件,因为所有其他数据都不会更改。谁能帮我做这个?本质上,我需要一种只写入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()
使用一些代码进行完全的重写,但应该完成以下工作:
相关问题 更多 >
编程相关推荐