Home > OS >  Use csv column as function arguments
Use csv column as function arguments

Time:06-09

csv

name;subnet
name_a;192.168.111.0/24
name_b;192.168.168.0/24
name_c;192.168.29.0/24

I try to run a function with a for loop for every column from a csv by passing the column values to function arguments. How should I do this?

I'm not sure if I have to import the csv content to a list, dict or if it is possible to directly use the columns as function arguments.

with open(csv_address_objects, mode='r', encoding='utf-8-sig') as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=';')
    list_of_csv = dict(csv_reader)

CodePudding user response:

Try this:

import pandas as pd

data = pd.read_csv("test.csv", sep=";")

names = data["name"].to_list()
subnets = data["subnet"].to_list()

def process_data(names, subnets):
    for name, subnet in zip(names, subnets):
        print(f"{name}: {subnet}")

if __name__ == "__main__":
    process_data(names, subnets)

CodePudding user response:

You should probably use pandas:

import pandas as pd
data = pd.read_csv(csv_address_objects, sep = ';')

You can then easily access columns, lines or any specific value. See: https://pandas.pydata.org/docs/getting_started/intro_tutorials/03_subset_data.html

  • Related