简体   繁体   中英

How to call a single function multiple times with different parameters in python?

list = ["a","b","c"]
def type(count):
    res2=list[count]
    for row1 in csv_reader1:   # Values imported from CSV
        res2=list[count]
        print(res2)
        res1 = str(row1)[1:-1]
        res3 = str(res1)[1:-1]
        print(res3)
type(0)
type(1)
type(2)

I want to call this type function, type(0) is being called, but then it exits and type(1) and type(2) are not being called. I've even tried with for loop

for i in range(0,2):
    type(i)
    i=i+1

Even this For doesn't work, it just calls type(0) and exits.

I've defined a list and I'm trying to iterate list for each value of imported from CSV. Kind of for-each in powershell - for-each list( print res2( = list) and print(each value in CSV) ) - This is what I'm trying to achieve. I'm new to Python. Any help would be greatly appreciated. Thanks in advance.

I assume you are creating a CSV reader something like this:

import csv
with open("myfile.csv") as f:
    csvreader1 = csv.reader(f)

This reader object can only be read once and is then used up. That's why your function doesn't do anything the 2nd and 3rd times. To be able to reuse the content, use list to read the whole file into memory.

with open("myfile.csv") as f:
    csv_content = list(csv.reader(f))

Alternatively, rewrite your function so that it reads the CSV each time.

letters = ["a","b","c"]
def print_data(i, filename):
    print(letters[i])
    with open(filename) as f:
        for row in csv.reader(f):   # Values imported from CSV
            print(str(row)[2:-2])

print_data(0, "myfile.csv")
list = ["a","b","c"]
file = open("C:/Users/data.csv") 
csv_reader = csv. reader(file)
def type(count):
    res2=list[count]
    
    for row1 in csv_reader:   # Values imported from CSV
        res2=list[count]
        print(res2)
        res1 = str(row1)[1:-1]
        res3 = str(res1)[1:-1]
        print(res3)

for i in range(0,2):
    type(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM