【发布时间】:2020-03-12 18:16:44
【问题描述】:
我对 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()
【问题讨论】:
-
不能只读取数据,修改元素,然后将结果写回文件吗?
-
我遇到了一个文件在读写模式下都打开的问题。我明白你的意思,谢谢你的想法
-
这很容易解决,不是吗?
-
对 python 来说是全新的
-
读取数据,保存/分配给某个变量,关闭文件,修改数据,写入输出。
标签: python file-handling