Home > Net >  Can't find the file from views.py
Can't find the file from views.py

Time:07-08

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.

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()

CodePudding user response:

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!

  • Related