0

I have a task in which I need to read from text file and call a function. The text file is following:

black,20,10,3,1
red,10,20,4,3
blue,10,-20,-4,3

My defined function takes five parameters, which are split in the text flile by commas. This is what I have so far:

with open(textfile) as source:
    for i in source.readlines():
        a = split(",")

But here I have no idea how to call the function with the read line from source.

Any ideas?

5
  • myfunc(a[0], a[1] ....)? Commented Nov 13, 2017 at 20:31
  • 1
    func(a[0],a[1],a[2],a[3],a[4])? or more briefly: func(*a)? Commented Nov 13, 2017 at 20:31
  • But a[0] gives me black, red and blue which is not what I want.. Commented Nov 13, 2017 at 20:35
  • @teepa: what do you want then? Commented Nov 13, 2017 at 20:38
  • "my defined function takes five parameters, which are split in the text file by commas" So I want the function to read five different values from one line, jump to next line and read five values and jump to the last line and read the values. Commented Nov 13, 2017 at 20:40

2 Answers 2

1

If your function is f, you could simply call f(*a).

Sign up to request clarification or add additional context in comments.

1 Comment

if I do indexes of a, they give me wrong things. For example, a[0] gives me black, red, blue. I would want it to give me black, 20, 10, 3, 1
0

I ended up with this and it is working.

def piirra_tiedostosta(tiedosto):
    with open(tiedosto) as source:
        for i in source.read().splitlines():
        c, a, r, n, w = i.split(",")
        a = int(a)
        r = int(r)
        n = float(n)
        w = int(w.strip())

Now I have all the variables separated from eachother, and I can call the function.

f(c, a, r, n, w)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.