Search code examples
pythonpython-3.xrelative-pathredditpraw

Python is not recognizing text file that is in the same directory?


My current project tree:

redditbot/  

-- commands/  
----__init__.py  
----comment_cache.txt  
----readcomments.py  

--mainbot.py

What I am attempting to do is read the comment_cache.txt file via open('comment_cache.txt')in the readcomments.py file., but for some reason I am getting a FileNotFoundError. Even when I try print(os.path.isfile('comment_cache.txt')), it just returns false.

Am I making a beginner mistake here? Maybe something that just I keep missing?

EDIT: I appreciate all the answers/comments, but I believe it is a problem with my Python interpreter itself. I kept moving around the file between the redditbot/ directory and the commands/ package until it just started working. Also for some reason whenever I call print(), PyCharm tells me that it is undefined...


Solution

  • I am assuming that mainbot.py is the entry point from where you run your application, so

    Problem I

    based on your project tree, the file should be available at path

    open('commands/comment_cache.txt')
    

    Problem II

    I kept moving around the file between the redditbot/ directory and the commands/ package until it just started working.

    You probably ended up placing the file in the same folder as your mainbot.py

    Problem III

    Also for some reason whenever I call print(), PyCharm tells me that it is undefined...

    There can be many posibilities behind this, check if the python interpreter is configured correctly and the python libraries are available on the PYTHONPATH for the project