从文本文件web2py读取

2024-10-01 11:19:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对web2py有问题。我有一个名为定义.txt在模块文件夹里。我试着用open("defVals.txt")(在与定义.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'

我做错什么了?我应该放在哪里定义.txt在

我用的是Ubuntu 12.10

谢谢

约旦

更新:

这是defaultValParser.py公司名称:

^{pr2}$

如果我导入它并从终端调用它(前提是我注释掉了gluon导入),它工作得很好,但是如果我从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'

Tags: inpytxtdefaulthomelinefileweb2py
1条回答
网友
1楼 · 发布于 2024-10-01 11:19:35

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

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

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

__file__是当前模块的文件名,使用的.dirname()提供模块所在的目录。我使用.abspath()来确保您在任何时候都有一个模块文件的绝对路径,从而避免了一些您可能会碰到的错误。在

moduledir是模块中的全局变量。在

相关问题 更多 >