python: file paths no longer work with imp
Question: I recently started using imports to better organize my code in python. My
original code in `file1.py` used the line:

    
    
    def foo():
        files = [f for f in os.listdir('.') if os.path.isfile(f)]
        print files
        #do stuff here....
    

Which referenced all the files in the same folder as the code, `print files`
showing the correct output as an array of filenames.

However, I recently changed the directory structure to something like this:

    
    
    ./main.py
    ./folder1/file1.py
    ./folder1/data_file1.csv
    ./folder1/data_file2.csv
    ./folder1/......
    

And in main.py, I use:

    
    
    import imp
    file1 = imp.load_source('file1', "./folder1/file1.py")
    .
    .
    .
    
    file1.foo()
    

Now, `files` is an empty array. What happened? I have tried absolute filepaths
in addition to relative. Directly declaring an array with `data_file1.csv`
works, but I can't get anything else to work with this import.

What's going on here?


Answer: When you do `os.listdir('.')` , you are trying to list the contents of `'.'`
(which is the current directory) , but this does not need to be the directory
in which the script resides, it would be the directory in which you were in
when you ran the script (unless you used `os.chdir()` inside the python
script).

You should not depend on the current working directory , instead you can use
`__file__` to access the path of the current script, and then you can use
[`os.path.dirname()`](https://docs.python.org/2/library/os.path.html#os.path.dirname)
to get the directory in which the script resides.

Then you can use
[`os.path.join()`](https://docs.python.org/2/library/os.path.html#os.path.join)
to join the paths of the files you get from `os.listdir()` with the directory
of the script and check if those paths are files to create your list of files.

Example -

    
    
    def foo():
        filedir = os.path.dirname(__file__)
        files = [f for f in (os.path.join(filedir, fil) for fil in os.listdir(filedir)) if os.path.isfile(f)]
        print files
        #do stuff here....
    

