Beginner question: use function to read text file
jstroud at ucla.edu
Tue Jun 27 03:23:03 CEST 2006
> I'm pretty stuck at the moment and wondering if anyone can spot the problem.
> Trying to create a function that will read a text file into a list and
> return that list.
> I wrote the following function and saved it as 'fileloader.py'
> def fileload(fname):
> dates =
> for line in infile:
> return dates,times,open,high,low,close
> Then I executed the following script (merge contract v1.py):
> import fileloader
> I then get the following error messages:
> Traceback (most recent call last)
> File "C:\Python24\test\merge contract v1.py", in line3, in?
> File ("C:\Python24\text\fileloader.py", in line2, in fileload
> UnboundLocalError: local variable 'open' referenced before assignment
> Script terminated
> Thanks for any help,
infile=open(fname) # <===
open= # <===
You have assigned open (which, by the way, is a builtin!) in a function
*after* you have referenced it. You have over-ridden the open name with
the assignment, but you have referenced it 'before assignment', as your
error mesage says. This is a favorite trip-up of newer pythong
programmers. Perhaps replace
with something like
UCLA-DOE Institute for Genomics and Proteomics
Los Angeles, CA 90095
More information about the Python-list