在Django应用程序中打开文件 [英] Open file in Django app

查看:350
本文介绍了在Django应用程序中打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 open()从Django应用程序打开一个文件。问题是, open()似乎使用我从其中运行 runserver 命令的任何目录作为根。 / p>

例如如果我从一个名为foo的目录运行服务器,这样

  $ pwd 
/ Users / foo
$ python myapp / manage.py runserver

open()使用 foo 作为根目录。



如果我这样做

  $ cd myapp 
$ pwd
/ Users / foo / myapp
$ python manage.py runserver

myapp 将成为根。



让我们的文件夹结构看起来像这样

  foo / myapp / anotherapp 

我想要打开位于 foo / myapp / anotherapp 从位于 foo / myapp / anotherapp 的脚本只需说

  file = open('./ baz.txt')

在我运行服务器的地方,我不得不说

  file = open('./ myapp / anotherapp / baz。文本') 

  file = open('./ anotherapp / baz.txt')


解决方案

解决方案已在收藏的Django提示与技巧问题中进行了描述。解决方案如下:

  import os 
module_dir = os.path.dirname (__file__)#获取当前目录
file_path = os.path.join(module_dir,'baz.txt')

这正是你提到的。



Ps。请不要覆盖文件变量,它是其中一个内建


I want to open a file from a Django app using open(). The problem is that open() seems to use whatever directory from which I run the runserver command as the root.

E.g. if I run the server from a directory called foo like this

$pwd
/Users/foo
$python myapp/manage.py runserver

open() uses foo as the root directory.

If I do this instead

$cd myapp
$pwd
/Users/foo/myapp
$python manage.py runserver

myapp will be the root.

Let's say my folder structure looks like this

foo/myapp/anotherapp

I would like to be able to open a file located at foo/myapp/anotherapp from a script also located at foo/myapp/anotherapp simply by saying

file = open('./baz.txt')

Now, depending on where I run the server from, I have to say either

file = open('./myapp/anotherapp/baz.txt')

or

file = open('./anotherapp/baz.txt')

解决方案

The solution has been described in the Favorite Django Tips&Tricks question. The solution is as follows:

import os
module_dir = os.path.dirname(__file__)  # get current directory
file_path = os.path.join(module_dir, 'baz.txt')

Which does exactly what you mentioned.

Ps. Please do not overwrite file variable, it is one of the builtins.

这篇关于在Django应用程序中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆