python - 在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
解决方案
这将返回文件的目录:
import os
os.path.dirname(os.path.abspath(__file__))
添加到它的文件名,你有文件路径。
推荐阅读
- reactjs - React State 变量没有更新
- javascript - 取消卸载时的 API 调用
- hadoop - Dask:从 HDFS 读取时,pyarrow/hdfs.py 返回 OSError: Getting symbol hdfsNewBuilder failed
- c# - 对象关系 C#
- reactjs - 在反应生产构建中生成没有散列文件名的构建
- java - 在java中,我如何告诉文件选择并打印一个随机单词?
- docker - 使用 Dockerfile 和 docker-compose 创建和运行 docker 容器
- react-native - react native返回上一页时如何保存状态?
- javascript - Javascript/Node/JSON 问题,为什么这不起作用?
- asp.net - 服务器违反了协议。Section=ResponseStatusLine 违规错误