0

I'm trying to use os.chdir() to change the working directory, and then import a file from that directory.

My code is

import os

os.chdir('./pythonfiles/')

from m269_db import show

show('''SELECT *
        FROM student;''')

However, for some reason the response I'm getting is

ModuleNotFoundError: No module named 'm269_db'

Using the print(os.getcwd()) command I get this response:

C:\Users\God\Desktop\unistuff\m269_u6

That is the correct directory. m269_u6 contains the m269_db.py file that otherwise works fine.

I can circumvent this by simply placing the files in the current directory but I can't seem to understand why I can't seem to import the files as I would expect to.

Dyneskye
  • 33
  • 5
  • 2
    Modify `sys.path`, not the cwd, when your goal is to import Python modules from a different directory. – Charles Duffy Mar 25 '22 at 14:06
  • 1
    `import sys` `sys.path.append('path/to/m269_u6')` – Raf Mar 25 '22 at 14:07
  • 1
    Think about it: If the Python interpreter worked the way you expect, it would be unsafe to do relative imports in any code that ever changed directories while it was running. So it makes more sense for the interpreter to lock down the working directory at startup by converting it to an absolute path so changing the cwd won't break imports. – Charles Duffy Mar 25 '22 at 14:07
  • 1
    @Raf, you mean `sys.path.append(os.path.join(os.getcwd(), 'pythonfiles')))`; `m269_u6.py` is a file in that directory, but it's the _directory_ that needs to be added. – Charles Duffy Mar 25 '22 at 14:08
  • 1
    @CharlesDuffy question is a bit confusing, first it mentions `pythonfiles` then after it says `m269_u6` *directory*, the file is `m269_db.py`... so, `whatever/path/to/correct/dir` – Raf Mar 25 '22 at 14:10

0 Answers0