This is a test version of Biostars. For the public version, visit https://www.biostars.org.
opening a file wih a function in python

Hey everybody, probably stupid question, but I do not understand what is wrong there, I guess I just do not know how to properly open a file in a function. Having my csv file in the folder, I want to make a list out of the it:

def make_OTU_list(csvfile):
    with open(csvfile, "rb") as list_input:
        csv = csv.reader(list_input)
        list_OTU = list(csv)[0]
        return list_OTU

make_OTU_list("OTU95_dominating.csv")

and I come back with that:

Traceback (most recent call last):
  File "labbook.py", line 35, in <module>
    make_OTU_list("OTU95_dominating.csv")
  File "labbook.py", line 31, in make_OTU_list
    csv = csv.reader(list_input)
UnboundLocalError: local variable 'csv' referenced before assignment

Can somebody solve my problem? Thanks a lot!

python csv

Have you tried to find the error message UnboundLocalError: local variable 'X' referenced before assignment on stackoverflow? I've just done a fast search and I've found several post related to this error.

I'd suggest you to surf on the internet before asking, in this way you will learn to solve the problems by yourself, and you'll develop your programming skills.

Hello sven.lemoinebauer!

We believe that this post does not fit the main topic of this site.

Not bioinformatics

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

2 answers

Look at the error message: "local variable 'csv' referenced before assignment"

  1. Have you imported the csv library?
  2. If yes, you should also use another variable name than csv to avoid confusion.
  3. You probably want to write the list of the function into a variable.

( 4. Not really a bioinformatic question )

import csv

def make_OTU_list(csvfile):
    with open(csvfile, "rb") as list_input:
        csv_reader = csv.reader(list_input)
        list_OTU = list(csv_reader)[0]
        return list_OTU

your_list = make_OTU_list("OTU95_dominating.csv")

Hey, thanks a lot. I had csv imported, and therefore there were confusion with my variable name. It works. Sorry if it was not the good place to post that.

Log in to answer this question.