简体   繁体   中英

specifying path for a file in python

I am trying to access a file(image) in python. But it says No such file or directory

This is my file structure- home->mrisa3->mrisa->src->program.py and the image

I have tried using absolute and relative path. But os.path.dirname(__file__) returns empty.

Here is my code:

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))

this is the output i am getting:

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'

But the line print(filename) is printing /home/apeksha/mrisa3/mrisa/src/image.jpeg

This will return the directory of the file:

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

add to it the file name and you have the file path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM