Python 写入CSV文件?

Python 写入CSV文件?,python,file-handling,Python,File Handling,我对python非常陌生,但我编写这段代码是为了读取csv文件,ping第一列中的ip地址列表,并使用csv writer函数将状态和ip地址输出到另一个csv文件。最终,我希望能够将状态写入新的csv文件,因为所有其他数据都不会更改。谁能帮我做这个?本质上,我需要一种只写入TEST2.csv中特定列的方法 import platform # For getting the operating system name import subprocess as sp # For execu

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

使用一些代码进行完全的重写,但应该完成以下工作:

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)

难道你不能读取数据,修改元素,然后将结果写回文件吗?我遇到了一个问题,即在读写模式下同时打开一个文件。我明白你的意思了,谢谢你的想法。不过,这是一个很容易修复的想法,不是吗?实际上,python是一个全新的概念。读取数据,保存/分配它到某个变量,关闭文件,修改数据,写输出。为什么要使用分号作为分隔符,而不是逗号呢?我经常使用包含
作为十进制符号的数据集。为了避免任何并发症,我使用了
作为数据分隔符作为我的“个人最佳实践”/首选工作流。