从文本文件的web2py阅读(Reading from a text file web2py)

2019-10-17 12:26发布

我在与web2py的一个问题。 我有一个名为defVals.txt一个文本文件,该文件在模块文件夹中。 我尝试从中读取数据,使用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'

Answer 1:

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

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

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

__file__是当前模块的文件名,使用.dirname()的,让你的目录中的模块。我使用.abspath()以确保你有你的模块文件的绝对路径在任何时候,远赴一些edgecases你本来打。

moduledir是你的模块中的一个全球性的。



文章来源: Reading from a text file web2py