英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论