Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python def从不同的脚本访问文件_Python - Fatal编程技术网

Python def从不同的脚本访问文件

Python def从不同的脚本访问文件,python,Python,首先是目录 file1.py | | --__init__.py file2.py some_package | | --__init__.py config.py settings.ini other_package | | --__init__.py access.py 现在,在config.py中有一个函数,readfromsetting(),它读取settings.ini,并返

首先是目录

file1.py
|
| --__init__.py 
    file2.py
    some_package
    |
    | --__init__.py
        config.py
        settings.ini
    other_package
    |
    | --__init__.py 
        access.py 
现在,在
config.py
中有一个函数,
readfromsetting()
,它读取
settings.ini
,并返回其中的内容。在
access.py
中,我导入了
config.py
(不,这不是您所想的,
access.py
成功导入了
config.py
),并尝试调用
readfromsetting()
函数,但Python抛出了错误

没有这样的文件或目录,“settings.ini”

因此,我的问题是,如何使用
config.py
access.py
读取
settings.ini
的内容

My
config.py

def readfromsetting():
    with open('settings.py', 'r') as file:
        return file.read()
我的
access.py

from some_package import config

def get_setting():
    return config.readfromsetting()
在执行
import
python时,会查看
sys.path
的内容以导入python脚本。但是,当您使用
open()
或其他方法读取文件,并给出相对路径时,Python会尝试将路径解析为相对于当前工作目录,它不会查看脚本所在的目录(除非该目录是工作目录)

您不应该依赖相对路径,而应该尽可能给出绝对路径

在您的情况下,如果您确信目录结构不会更改(即
settings.ini
将始终位于
config.py
存在或
settings.py
存在的目录中),则可以使用
\uuuuu file\uuu
变量访问文件的路径,然后使用它创建
设置.ini的绝对路径。范例-

import os.path
dirpath = os.path.abspath(os.path.dirname(__file__))
settings_file = os.path.join(dirpath,'settings.ini')
你的问题是:

def readfromsetting():
  with open('settings.ini', 'r') as file:
    return file.read()
“settings.ini”是一个相对路径。如果您要查找的文件位于同一目录中,这将非常有效。由于您从access.py调用此方法,并且access.py不在此目录中,因此它找不到settings.ini文件


我建议您在open方法中使用settings.ini文件的绝对路径。如果您确定只从access.py中调用此方法,还可以编辑另一个答案中提到的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

请提供程序重要部分的工作代码(config.py with readfromsetting()和access.py)。第一种猜测是,您在readfromsetting()中使用了一个相对路径,但该路径不起作用,因为您的access.py位于另一个包/目录中。您可能在打开的调用中指的是settings.ini,而不是settings.py。