Search code examples
pythonimportmoduleioerror

Errno 2 file not found when calling a function from a different .py file


I made a function that reads from a file and saves it's data in an array.

This function is in Posts.py:

index = 'Forum/Topics/index.txt'

def loadTopicNames():
    with open(index, 'r') as file:
        data = file.readlines()
        for row in data:
            row = row.replace('\n', '')
            topicNames.append(row)

This function works, doesn't have problems with the file location. But when I import the Posts.py module in my Forum.py module, and execute it from Forum.py, I get this error:

with open(index, 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'Forum/Topics/index.txt'

Here is the relevant code from Forum.py:

import Posts
Posts.loadTopicNames()

Note: I found some solutions on stackoverflow already, but they mostly include making the path absolute, which is not an option here. Posts.py and Forum.py are in the same folder.

This is sort of a representation of where the files are in the project:

Project/Forum.py

Project/Posts.py

Project/Forum/Topics/index.txt

Project/otherStuff...

Edit: found the problem... The working directory for the Forum.py wasn't right, and that was the reason it messed everything up. It had wrong working directory because when I first made the module, I made it in a wrong folder. Then when I realized my mistake, I just copied it to the right place, but the working directory stayed the same...


Solution

  • This code will work only if you run python Forum.py in the same directory in which the Forum directory lives.

    UPD: I recreated your case on my laptop, and everything works fine. Please check the code:

    Posts.py:

    index = 'Forum/Topics/index.txt'
    
    def loadTopicNames():
        with open(index, 'r') as file:
            data = file.readlines()
            for row in data:
                print(row)
    

    Forum.py:

    import Posts
    Posts.loadTopicNames()
    

    index.txt:

    test text
    

    Project directory:

    $ ls -R
    Forum     Forum.py  Posts.py
    
    ./Forum:
    Topics
    
    ./Forum/Topics:
    index.txt
    

    Run & output:

    $ pwd
    /Users/myuser/Forum
    $ python Forum.py 
    test text