简体   繁体   中英

How can I get the .img file from the path directory in python?

I have a file with the extension of .img ,in this path of my OS /home/amanda/workspace/FX36.img . I dont know how can I access that file.img in python and use this file.img as a body in my code.

        js_body = dict()
        file_path ="/home/amanda/workspace/FX36.img"
        img=open(file_path ,"r")
        js_body["File"] = img
        js_res = self._post(rest_uri, js_body)
        return js_res

I dont know what should I put instead of

img=open(file_path ,"r")

till I have

js_body["File"] = FX36.img

I will be grateful if someone could help me.

img=open(file_path ,"r")

It only creates the stream. You need to call method read() to get actual content.

img = open(file_path, 'r').read()

If you want bytes use rb flag instead.

img_bytes = open(file_path, 'rb').read()

You also need to dispose the opened stream.

with open(file_path, 'r') as file:
    img = file.read()

I'd also advise against using raw paths in code. It'll crash on any OS, which uses different path conventions. Use pathlib instead.

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