【问题标题】:Python- working with files in multiple directoriesPython-处理多个目录中的文件
【发布时间】:2013-02-23 18:53:51
【问题描述】:

我意识到这可能被认为是其他一些问题的重复问题,但我已经花了一个多小时阅读各种页面和文档,但仍然不明白这里发生了什么。

我正在尝试处理多个目录中的 python 文件;我基本上有这个:

myproject/
    __init__.py
    some_file.py
    some_data.dat
    tests/
        __init__.py
        test_some_file.py

test_some_file.py是命令行运行的,顾名思义,是为了运行some_file.py中包含的代码,需要导入。但是,我似乎不能这样做。

我试过了:

from myproject import some_file

还有

from .. import some_file

我确实设法使用sys.path 让它运行,但根据我所读到的内容,这似乎不是正确的做事方式。

其次,当我使用sys.path 运行它时,我得到一个错误,它找不到some_file.py 使用的some_data.dat

【问题讨论】:

    标签: python import package


    【解决方案1】:

    这是 Python 程序员常问的问题。问题是 Python 不能很好地处理包内的脚本。在过去的几个版本中,情况有所改善,但很多时候仍然没有做正确的事情。

    我认为最好的答案是限制运行 test_some_file.py 的位置,并使用 Python 解释器的 -m 参数。即切换到myproject上面的目录,然后运行python -m myproject.tests.test_some_file。这是唯一不会与sys.path 混淆的方法。

    这将允许您的任一导入行正常工作。 PEP 8 目前建议始终使用绝对导入,因此第一个版本可能比使用 .. 的相对版本更好。

    【讨论】:

    • 这对我的第一个问题有所帮助;第二个问题,some_file.py 找不到 some_data.dat 是否有原因?
    • @Retsam:你的问题模块中的 cwd 是什么?
    • @Retsam: some_file.py 可以在os.path.split(__file__)[0]目录下找到some_file.dat。
    • @martineau:使用__file__ 是个好主意,但您需要使用os.path.dirname 而不是split
    • @Blckknght:那会更简洁,但你 split(hairs) ;-)
    【解决方案2】:

    对于像你这样的情况,我将some_file.py的目录添加到sys.path(临时)。

    代码:

    import sys, os
    dirname = os.path.dirname(                 # going up by 1 directory
                       os.path.dirname(        # going up by 2 directories
                                sys.argv[0]))
    sys.path.append(dirname)
    import some_test
    

    【讨论】:

      猜你喜欢
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      相关资源
      最近更新 更多