正在写入CSV文件?

问题描述 投票:-1回答:1

我对python还是很陌生,但是我编写了这段代码来读取一个csv文件,对第一列中的ip地址列表执行ping操作,然后使用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 file-handling
1个回答
0
投票

使用您的一些代码进行了完全的重新编写,但是应该可以完成工作:

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)
© www.soinside.com 2019 - 2024. All rights reserved.