1

In Python, If I want to import a file from a different directory then I'm supposed to do that,

import sys
sys.path.append("/path")

Now,

I have two files to be imported,

File1.py and File2.py,

these are the locations of the files,

MyFiles/File1.py
MyFiles/File2.py

Now, If I want to import these two files, I'd do that

from MyFiles import File1
from MyFiles import File2

this shouldn't work because I haven't defined the path for these files using sys.path

But when I am running my code the files are importing successfully without defining the path using sys.path

This is the code,

from __future__ import print_function

import sys
import os
import hashlib
import struct #Interpret strings as packed binary data
import getopt #for Runtime arguments

from MyFiles import File1
from MyFiles import File2

Eventhough, I haven't defined sys.path , this code is still successfully importing the files from the directory.

and the path is not already available in sys.path

['C:\\Users\\Sufiyan\\Desktop\\MyFolder', 'C:\\Windows\\SYSTEM32\\python33.zip', 'C:\
\Python33\\DLLs', 'C:\\Python33\\lib', 'C:\\Python33', 'C:\\Python33\\lib\\site-
packages']

It is clear that the path, C:\\Users\\Sufiyan\\Desktop\\MyFolder\\MyFiles is not there.

then why this code is working ?

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110

2 Answers2

1

that path isn't there, but the parent path 'C:\\Users\\Sufiyan\\Desktop\\MyFolder' is. when you do

from MyFiles import File1

it's going to try to append the path of the module to the existing paths, so it will take the above path, add 'MyFiles' to it, and try to import File1 from that module (either a file, or from __init__.py in the MyFiles directory).

you can treat a module path, as very similar to a file path. if that exists as a subdirectory under anything in sys.path, that's where it will go to get it.

Corley Brigman
  • 11,633
  • 5
  • 33
  • 40
0

It's possible that the folder they live in is already in your path. You can check by doing the following:

import sys

sys.path

Give that a shot.

Benjooster
  • 544
  • 2
  • 6
  • 20