Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't find the file from views.py

I am stuck with a really weird problem.

I have a file called: "test.txt".

It is in the same directory with views.py. But I can’t read it… FileNotFoundError.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But if I create read_file.py in the same directory with views.py and test.txt, it works absolutely fine.

What is wrong with views? Is this some sort of restriction by Django?

This code works on read_file, doesn’t work on views.py:

fkey = open("test.txt", "rb")
key = fkey.read()

>Solution :

I think the problem may be relative vs absolute file handling. Using the following Python snippet, you can work out where the interpreter’s current working directory is:

import os
print(os.getcwd())

You should notice it’s not in the same directory as the views.py, as views.py is likely being invoked/called from another module. You may choose to change all your open calls to include the whole path to these files, or use an implementation like this:

import os

# This function can be used as a replacement for `open`
# which will allow you to access files from the file.
def open_relative(path, flag="r"):

    # This builds the relative path by joining the current directory
    # plus the current filename being executed.
    relative_path = os.path.join(os.path.dirname(__file__), path)

    return open(relative_path, flag) # return file handler

Then, this should work:

fkey = open_relative("test.txt", "rb")
key = fkey.read()

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading