Home > Mobile >  pdf.savefig gives "An error opening...This file is already open...corrupted" when saving P
pdf.savefig gives "An error opening...This file is already open...corrupted" when saving P

Time:09-27

I am trying to plot pie graphs using my a CSV file I have created via webscrapping. I am able to print/show the pie graphs but unable to save it on PDF file. I tried removing plt.show()/adding it back after pdf.savefig(fig) but that did not work. Here is my Code:

(Part of the CSV file is below the Python code)

from cmath import inf
from bs4 import BeautifulSoup
import requests
from csv import writer
import pandas as pd
#%matplotlib inline
import numpy as np
import re
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(palette="Paired")
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.backends.backend_pdf

data_frame = pd.read_csv("UFCstats.csv")

data_frame.head(500)
df = pd.DataFrame(columns=["totalwins","totalloss"], data=data_frame.head(500))
pdf = matplotlib.backends.backend_pdf.PdfPages('pic.pdf')

for ind in df.index:
    fig, ax = plt.subplots(1,1)
    fig.set_size_inches(5,5)
    df.iloc[ind].plot(kind='pie', ax=ax, shadow=True, title=data_frame.iloc[ind]["Fullname"], explode=[0.03,0.03], autopct='%1.1f%%')
    ax.set_ylabel("total wins are "   str(data_frame.iloc[ind]["totalwins"]))
    ax.set_xlabel("total losses are "   str(data_frame.iloc[ind]["totalloss"]))
    pdf.savefig(fig)
plt.show()

UFCstats

Error when trying to open the PDF file: "There was an error opening this document. This file is already open or in use by another application"

CodePudding user response:

you need to close the pdf file at the end of the code (outside the for loop). This will close the file and you can open it without issues. Use pdf.close() to close the file.

  • Related