Skip to content

write_image() doesn't work with pathlib.Path() objects #2753

Closed
@sedoris

Description

@sedoris

This code works as expected:

import plotly.express as px
fig = px.scatter(x=[1,2,3], y=[1,2,3])
# Works with a string
fig.write_image('test.png', format='png')

However, if you try to use a pathlib.Path object instead of a string, you get an exception:

import plotly.express as px
import pathlib
fig = px.scatter(x=[1,2,3], y=[1,2,3])
# Doesn't work with a Path
fig.write_image(pathlib.Path('test.png'), format='png')

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-402d35877fa7> in <module>
      6 fig.write_image('test.png', format='png')
      7 # Doesn't work with a Path
----> 8 fig.write_image(pathlib.Path('test.png'), format='png')

/opt/conda/lib/python3.8/site-packages/plotly/basedatatypes.py in write_image(self, *args, **kwargs)
   3249         import plotly.io as pio
   3250 
-> 3251         return pio.write_image(self, *args, **kwargs)
   3252 
   3253     # Static helpers

/opt/conda/lib/python3.8/site-packages/plotly/io/_kaleido.py in write_image(fig, file, format, scale, width, height, validate, engine)
    258             f.write(img_data)
    259     else:
--> 260         file.write(img_data)
    261 
    262 

AttributeError: 'PosixPath' object has no attribute 'write'

This code works, though:

import plotly.express as px
import pathlib
fig = px.scatter(x=[1,2,3], y=[1,2,3])
fig.write_image(str(pathlib.Path('test.png')), format='png')

So, at a minimum this could be fixed by checking if file is an instance of pathlib.Path and if so, cast it as a str.

PS Thanks for all the hard work on this project, it's great watching it continually improve. This isn't a particularly important issue for me, just wanted to add it to the list of potential fixes for the next version in case others are also interested.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions