Search code examples
pythoniotelegram

How to check that i is 0 in io.BytesIO().seek(i)?


I make lineplot to send for sending to Telegram. First sending is ok.

Second time I get error: BadRequest: File must be non-empty

How to check what i = 0 (position of cursor) in seek(i)?

sns.lineplot(x=x, y=y);
plt.title('test plot');

plot_object = io.BytesIO()
plt.savefig(plot_object)
plot_object.seek(0)

plot_object.name = 'test_plot.png'
plt.close()

bot.sendPhoto(chat_id, plot_object)

Solution

  • You can use plot_object.tell() to check cursor position before and after seeking.

    Test Code:

    import io
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    x = [1, 2, 3, 4, 5]
    y = [2, 4, 1, 5, 2]
    
    sns.lineplot(x=x, y=y)
    plt.title('test plot')
    
    plot_object = io.BytesIO()
    plt.savefig(plot_object)
    
    print("Before seek:", plot_object.tell()) # check cursor position
    plot_object.seek(0) # seek to the start 
    print("After seek:", plot_object.tell())
    
    #plt.show() 
    plt.close()
    

    Output:

    Before seek: 25771
    After seek: 0