Python - 如何打开模块内的文件?

Python - How to open a file inside a module?

我的程序中有这样的东西: 名为 'OpenFileinaModule' 的文件夹中的主脚本 main.py。其中有一个名为 'sub' 的文件夹,其中包含一个名为 subScript.py 的脚本和一个由 subScript.py 打开的文件 xlFile.xlsx。

OpenFileinaModule/
             main.py
             sub/
             __init__.py   (empty)
             subScript.py
             xlFile.xlsx

代码如下:

sub.Script.py:

import os, openpyxl

class Oop:
    def __init__(self):
        __file__='xlFile.xlsx'
        __location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))
        print os.path.join(__location__, __file__)

        self.wrkb = openpyxl.load_workbook(os.path.join(__location__, 
__file__),read_only=True)

main.py:

import sub.subScript
objt=sub.subScript.Oop()

当我执行main.py时,出现错误:

IOError: [Errno 2] No such file or directory: 'C:\Users\...\OpenFileInaModule\xlFile.xlsx'

跳转子文件夹... 我试过了

__file__='sub/xlFile.xlsx'

但是 "sub" 文件夹被复制了:

IOError: [Errno 2] No such file or directory: 'C:\Users\...\OpenFileInaModule\sub\sub/xlFile.xlsx'

如何使用 main.py 中的 subScript.py 打开 xlFile.xlsx?

您正在用 __file='xlFile.xlsx' 覆盖 __file__,您是要这样做吗?


我想你想要这样的东西

import os
fname = 'xlFile.xlsx'
this_file = os.path.abspath(__file__)
this_dir = os.path.dirname(this_file)
wanted_file = os.path.join(this_dir, fname)

我建议始终使用文件的绝对路径,尤其是当您在 windows 上时,如果文件位于不同的驱动器上,则相对路径可能没有意义(我实际上没有想一想如果你向它询问设备之间的相对路径它会做什么)。

请避免使用 __file____location__ 来命名您的变量,这些更像是内置变量,可能会引起混淆。

注意这里:

__location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))

你没有包含sub目录,上面只加入了CWD+os.path.dirname(__file__)。这不会让您进入文件。请阅读 os.path.dirname 的文档:os.path.dirname(__file__) returns 此处为空字符串。

def __init__(self): 
    file = 'xlFile.xlsx'
    location = os.path.join('sub', file)
    location = os.path.abspath(location)             # absolute path to file
    location = os.path.realpath(location)           # rm symbolic links in path 
    self.wrkb = openpyxl.load_workbook(location)