2017-07-11 28 views
1

我在我的程序中有这样的东西: 一个名为'OpenFileinaModule'的文件夹中的主脚本main.py。有一个名为'sub'的文件夹,里面有一个名为subScript.py的脚本和一个由subScript.py打开的文件xlFile.xlsx。Python - 如何打开模块内的文件?

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' 

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

回答

0

你压倒一切__file____file='xlFile.xlsx',你的意思是做到这一点?


我想你想要像

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时,如果在一个相对路径可能没有什么意义文件在不同的驱动器上(我实际上不知道如果你问它设备之间的相对路径会做什么)。

+1

这正是我所期待的。 这是常见的事情吗? –

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)