[英]specifying path for a file in 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__))
添加文件名,你就有了文件路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.