Python如何在模块内打开文件?

2024-09-29 23:30:54 发布

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

我的程序里有这样的东西: 主脚本主.py在名为“OpenFileinaModule”的文件夹中。里面有一个名为“sub”的文件夹,其中有一个名为下标.py还有一个文件xlFile.xlsx文件,由打开下标.py. 在

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

代码如下:

在sub.Script.py公司名称:

^{pr2}$

在主.py公司名称:

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

当我执行任务时主.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'

如何打开xlFile.xlsx文件与下标.py从main.py?在


Tags: 文件nopy文件夹名称main公司xlsx
2条回答

请避免使用__file____location__来命名变量,它们更像是内置变量,可能会导致混淆。在

请注意:

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

您没有包含sub目录,并且上面的只连接CWD+os.path.dirname(__file__)。这不能让你找到文件。请阅读^{}的文档:os.path.dirname(__file__)在这里返回一个空字符串。在

^{pr2}$

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

相关问题 更多 >

    热门问题