从文本文件web2py读取



我遇到web2py的问题。我有一个名为defvals。txt的文本文件,在modules文件夹中。我尝试从它读取,使用open("defVals.txt")(在模块在相同的导演defVals.txt),但我得到错误:

Traceback (most recent call last):
 File "/home/jordan/web2py/gluon/restricted.py", line 212, in restricted
   exec ccode in environment
File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 67,     in <module>
 File "/home/jordan/web2py/gluon/globals.py", line 188, in <lambda>
self._caller = lambda f: f()
File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 13, in index
  defaultData = parse('defVals.txt')
File "applications/randommotif/modules/defaultValParser.py", line 6, in parse
 lines = open(fileName)
IOError: [Errno 2] No such file or directory: 'defVals.txt'

我做错了什么?defVals.txt

放在哪里?

我正在使用Ubuntu 12.10

谢谢,约旦

更新:

这是defaultValParser.py的源代码:

import itertools
import string
import os
from gluon import *
from gluon.custom_import import track_changes; track_changes(True)
#this returns a dictionary with the variables in it.
def parse(fileName):
    moduleDir = os.path.dirname(os.path.abspath('defaultValParser.py'))
    filePath = os.path.join(moduleDir, fileName)
    lines = open(filePath, 'r')
    #remove lines that are comments. Be sure to remove whitespace in the beginning and end of line
    real = filter(lambda x: (x.strip())[0:2] != '//', lines)
    parts = (''.join(list(itertools.chain(*real)))).split("<>")
    names = map(lambda x: (x.split('=')[0]).strip(), parts)
    values = map(lambda x: eval(x.split('=')[1]), parts)
    return dict(zip(names, values))

如果我导入它并从终端调用它(如果我注释掉胶子导入),它可以正常工作,但如果我从web2py控制器调用它,它完全失败了:

Traceback (most recent call last):
  File "/home/jordan/web2py/gluon/restricted.py", line 212, in restricted
   exec ccode in environment
  File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 71, in <module>
  File "/home/jordan/web2py/gluon/globals.py", line 188, in <lambda>
  self._caller = lambda f: f()
  File "/home/jordan/web2py/applications/randommotif/controllers/default.py", line 17, in index
  defaultData = parse('defVals.txt')
  File "applications/randommotif/modules/defaultValParser.py", line 6, in parse
 IOError: [Errno 2] No such file or directory: 'defVals.txt'

根据模块的__file__路径使用绝对路径:

moduledir = os.path.dirname(os.path.abspath('__file__'))
# ..
defaultData = parse(os.path.join(moduledir, 'defVals.txt'))

__file__是当前模块的文件名,使用其中的.dirname()给出模块所在的目录。我使用.abspath()来确保你的模块文件在任何时候都有一个绝对路径,避免一些边缘,因为你可能会碰到其他情况。

moduledir是你模块中的全局变量

相关内容

  • 没有找到相关文章

最新更新