Beginner question: use function to read text file
gherron at islandtraining.com
Tue Jun 27 03:30:43 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 =
Here's the problem. You are using the name "open" it two contexts. The
variable named "open" is a local variable, and as such it hides the
builtin function of the same name used to open files. (It does not
matter that the use of "open" as a function precedes the use of "open"
as a variable name. Python is rather strict about this. If you use a
variable in a def, then ANYWHERE in that def, that name refers to the
local variable and hides any uses of the name from enclosing scopes.)
If that last makes sense, good. If not, then just follow this rule:
Choose your variable names to be different than any builtin names -- or
at least different than any of the builtin names you intend to use.
> 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,
More information about the Python-list