Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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从目录导入模块,读取文件时出错_Python_Python 3.x_Import_Module_Python 3.6 - Fatal编程技术网

Python从目录导入模块,读取文件时出错

Python从目录导入模块,读取文件时出错,python,python-3.x,import,module,python-3.6,Python,Python 3.x,Import,Module,Python 3.6,我正在使用python 3.7 这是我的项目文件结构 在m.py文件中: 在reader.py文件中: 在readme.txt文件中: 运行m.py文件时,出现以下错误: 如何修复此错误?在Python中使用文件的相对路径时,该路径相对于当前工作目录cwd,而不是文件的当前位置 当前工作目录是启动脚本的路径。在您的例子中,cwd是一个包含脚本m.py的文件夹 您需要将路径更改为readme.txt。一个健壮的选项是获取脚本reader.py的路径,并使用它确定文件readme.txt的路径。您可

我正在使用python 3.7

这是我的项目文件结构

在m.py文件中:

在reader.py文件中:

在readme.txt文件中:

运行m.py文件时,出现以下错误:


如何修复此错误?

在Python中使用文件的相对路径时,该路径相对于当前工作目录cwd,而不是文件的当前位置

当前工作目录是启动脚本的路径。在您的例子中,cwd是一个包含脚本m.py的文件夹

您需要将路径更改为readme.txt。一个健壮的选项是获取脚本reader.py的路径,并使用它确定文件readme.txt的路径。您可以使用模块属性_文件_;获取模块的完整文件路径,然后提取目录名

新阅读器.py

导入操作系统 def read_文件: 自述文件\路径=os.path.joinos.path.dirname \文件\自述文件'readme.txt' 使用openreadme_路径,“r”作为f: d=f.read 返回d 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': 打印读取文件
文件路径相对于您从中调用条目文件python m.py的路径进行解析

要解决此问题,您可以使用readme.txt的绝对路径,或者将“readme.txt”更改为“aa/readme.txt”

要找出应用相对路径结尾的绝对路径,可以从reader.py执行以下操作:

导入操作系统 printos.getcwd
.
├── aa
│   ├── reader.py
│   └── readme.txt
└── m.py

1 directory, 3 files
import aa.reader as reader    
reader.read_file()
def read_file():
    with open('readme.txt', 'r') as f:
        d = f.read()
    return d


if __name__ == '__main__':
    print(read_file())
this is the content of readme
ranick@r-ubt:~/Desktop/kk$ python m.py 
Traceback (most recent call last):
  File "m.py", line 4, in <module>
    reader.read_file()
  File "/home/ranick/Desktop/kk/aa/reader.py", line 3, in read_file
    with open('readme.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'readme.txt'