How can I read a media file from a .py file using Django?
I can read the file a.txt
like this:
text = open('a.txt', 'rb').read()
But when I put a.txt
in a folder media
this doesn't work:
text = open('/media/a.txt', 'rb').read()
I am getting the following error:
IOError at /
[Errno 13] file not accessible: '/media/a.txt'
How can I read a file from a directory media
?
a source to share
Initial /
means it is an absolute path accessible from the root of the filesystem. If you want to read a file from the project path, you will need to start the file name with the project path, or use in __file__
conjunction with functions in os.path
to create the appropriate relative or absolute path.
a source to share
You cannot read static files from your application code in Google App Engine. Files marked static are served from different servers and are not part of your application. If your application needs to read them and they don't need to be served directly to users, don't make them static. If you need to both serve them directly to users and read them in python code, you need to include 2 copies in the project, one marked as static and the other not.
a source to share