1

I'm just starting Python (3.3) on Windows 7, and the book I've been using (Learning Python, by Mark Lutz) says I can also run Python modules by using the exec(...) function. This is the code the author presents:

>>> exec(open('script2.py').read())

The error this code shows is:

FileNotFoundError: [Errno 2] No such file or directory: 'script2.py'

To emphasise, I do have the PYTHONPATH variable set, and therefore the import function works properly: it doesn't show any error messages after importing a module.

I have provided the screenshot: https://i.sstatic.net/ZzDLE.png

To prove that the file imports normally, I will take a screenshot when importing that file: https://i.sstatic.net/gLiH4.png

Even though I don't believe there is something wrong with the Pathway, but with the function itself... Help!

11
  • Do you actually have a script2.py in the working directory? Commented Aug 14, 2013 at 23:45
  • compare the output of: import sys; print(sys.path) for both cases. You might not be in the folder you think you are Commented Aug 14, 2013 at 23:49
  • Not sure what to compare, I can normally import sys and script2.py. Yes, I do have a "script2.py" in the working directory which is shown in the second picture. (Can you see the pictures, do I have to upload to somewhere else?) Commented Aug 14, 2013 at 23:49
  • What is the location of script2.py? Commented Aug 14, 2013 at 23:51
  • No, just because you can import it (its somewhere in the maze of python import paths) doesn't mean its in the local directory. Exit python and do a dir. Commented Aug 14, 2013 at 23:52

1 Answer 1

1

open('xyz') does not search the various python import paths. If you give a relative path name, it starts with the current working directory, appends your path and looks there. If you give an absolute path, it ignores the current directory.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.