首页 > 解决方案 > 在python中指定文件的路径

问题描述

我正在尝试在 python 中访问文件(图像)。但它说没有这样的文件或目录

这是我的文件结构- home->mrisa3->mrisa->src->program.py 和图像

我尝试过使用绝对路径和相对路径。但os.path.dirname(__file__)返回空。

这是我的代码:

import base64
import os
def basesix4(file):
    encoded_string = ""

    with open(file, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())

    return encoded_string

if __name__ == "__main__":
    file = os.getcwd()
    filename=os.path.join(file,'image.jpeg')
    print(filename)
    print(basesix4(filename))

这是我得到的输出:

Traceback (most recent call last):
  File "basesix4.py", line 15, in <module>
    print(basesix4(filename)[:70])
  File "basesix4.py", line 6, in basesix4
    with open(file, "rb") as image_file:
FileNotFoundError: [Errno 2] No such file or directory: '/home/apeksha/mrisa3/mrisa/src/image.jpeg'

但是这条线print(filename)正在打印 /home/apeksha/mrisa3/mrisa/src/image.jpeg

标签: pythonfilesystems

解决方案


这将返回文件的目录:

import os
os.path.dirname(os.path.abspath(__file__))

添加到它的文件名,你有文件路径。


推荐阅读