从文本文件web2py中读取

时间:2012-12-23 22:14:39

标签: python file 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'

1 个答案:

答案 0 :(得分:2)

使用基于模块的__file__路径的绝对路径:

moduledir = os.path.dirname(os.path.abspath('__file__'))

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

__file__是当前模块的文件名,使用.dirname()为您提供模块所在的目录。我使用.abspath()确保您拥有绝对路径您的模块文件始终处于远离您可能遇到的一些边缘的情况下。

moduledir是您模块中的全局。