【问题标题】:Python - How to open a file inside a module?Python - 如何在模块内打开文件?
【发布时间】:2017-07-11 17:01:51
【问题描述】:

我的程序中有这样的内容: 名为“OpenFileinaModule”的文件夹中的主脚本 main.py。里面有一个叫做'sub'的文件夹,里面有一个叫做subScript.py的脚本和一个文件xlFile.xlsx,它是由subScript.py打开的。

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'

但随后“子”文件夹被复制:

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

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

【问题讨论】:

    标签: python openpyxl


    【解决方案1】:

    请避免使用__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__) 在此处返回一个空字符串。

    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)
    

    【讨论】:

      【解决方案2】:

      你要用__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 上时,如果文件位于不同的驱动器上,相对路径可能没有意义(我实际上不知道如果您要求它提供设备之间的相对路径)。

      【讨论】:

      • 这正是我想要的。这是常见的事情吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多