读取模块内的文件

huangapple go评论82阅读模式
英文:

Reading a file within module

问题

# module1.py

[...]
def myfunction():
    with open('externalfile.xml', 'r') as fh:
        xml = fh.read()
    return xml
英文:

I'm struggling with - I think - a very simple problem.

I'm developing a custom package with a structure like this:

mypackage
|      |-> __init__.py
|      |-> module1.py
|      |-> module2.py
|      |-> module3.py
|      |-> externalfile.xml

The external file is read by a fuction in module1.
I can easily and obviously do it if I launch module1 in terminal. But when I try to launch that function within another script, I have a FileNotFoundError traceback.

My question is: why in this situation I can't be able to open a file that lives witin the package itself?

# module1.py

[...]
def myfunction():
    with open('externalfile.xml', 'r') as fh:
        xml = fh.read()
    return xml
# __init__.py

import mypackage.module1
[...]
# myOtherScript.py

from mypackage import module1

[...]
script = module1.myfunction()

Error:

Traceback (most recent call last):
  File --myOtherScript.py--, line xx, in <module>
    from mypackage import module1
  File "-\Programs\Python\Python310\lib\site-packages\mypackage\__init__.py", line xx, in <module>
    with open('exeternalfile.xml', 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'externalfile.xml'

答案1

得分: 1

# module1.py

import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # 返回您的包文件夹的绝对路径

def myfunction():
    with open(os.path.join(BASE_DIR, "externalfile.xml"), 'r') as fh:
        xml = fh.read()
    return xml
英文:
# module1.py

import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # Returns the absolute path to your package folder

def myfunction():
    with open(os.path.join(BASE_DIR, "externalfile.xml"), 'r') as fh:
        xml = fh.read()
    return xml

huangapple
  • 本文由 发表于 2023年3月7日 16:23:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定