IOError:[Errno 13]权限被拒绝:'Test.xlsx'

时间:2018-12-11 08:49:15

标签: python ioerror

我的程序的目标是从Test.xlsx文件中读取工作表SNR_COPY1,使用数据进行一些计算,然后将其写入Test.xlsx中的新工作表...现在,昨天我的代码运行良好,但是当我重新运行它时,出现了上面提到的错误。python脚本和xlsx文件都放置在Documents中(不确定它有多重要,但是我在Windows上工作)。我的代码:

  import numpy as np
from numpy import pi, r_
import matplotlib.pyplot as plt
from scipy import optimize
from scipy.optimize import curve_fit
import pandas as pd
from pandas import DataFrame
import copy


#version in which all data will be read from the excelfile. The resulting fitparameters will be written into the excisting excelfile.

def snr_fitting_excel(number_of_altitude_points, row_begin_position_of_data, number_of_wavelengths):

# (0,0) in python  = (2,1) in excel

   n_alt = number_of_altitude_points
   n_lambda = number_of_wavelengths
   begin = row_begin_position_of_data
   end = begin + n_alt
   xlsx = pd.ExcelFile('Test.xlsx')
   df = pd.read_excel(xlsx, 'SNR-COPY1')
   xlsx_copy = copy.deepcopy(xlsx)

#print the beginning point of your data. This ensures that you are working at the correct position in the excel file   
   print(df.iat[11,2])
   d = (n_alt, n_lambda)

   #each row of height will represent the data for a given alltitude (height[0] = 5km data,...)
   height = np.zeros(d, dtype=int)
#   print(height)
   for j in range(begin, end):
      for i in range(2,10):
         height[j-begin][i-2] = (np.around(df.iat[j,i], decimals =0))
   height = np.array(height)   
#array with the different wavelengths at which the data was taken   
   wavelengths = np.array([400, 450, 500, 550, 600, 650, 700, 800])
   parameter_values = []

#fit the points with the desired function from above
   for i in range(0, len(height)):
        popt, pcov = curve_fit(fitfunc_polynome_OP_BL, wavelengths, height[i])


        fig = plt.figure()
        plt.plot(wavelengths, height[i], 'o')
        plt.plot(wavelengths, fitfunc_polynome_OP_BL(wavelengths, *popt), 'r-', label ='fit: a=%5.3f, b=%5.3f, c=%5.3f, d=%5.3f, e=%5.3f, g=%5.3f, h=%5.3f, i=%5.3f' % tuple(popt))
        plt.xlabel("Wavelength (nm)")
        plt.ylabel("SNR")
        plt.title("OP-BL-SNR fitting without data cut-off alltitude: " + str((i+1)*5) + "km")
        fig.savefig("snr_op_fit_bl" + str((i+1)*5) +".pdf")
        parameter_values.append(popt)
        print(str((i+1)*5))
        print(popt) 


   parameter_values_to_export = {'a': [parameter_values[0][0], parameter_values[1][0], parameter_values[2][0], parameter_values[3][0], parameter_values[4][0], parameter_values[5][0], parameter_values[6][0], parameter_values[7][0], parameter_values[8][0], parameter_values[9][0], parameter_values[10][0], parameter_values[11][0], parameter_values[12][0], parameter_values[13][0], parameter_values[14][0], parameter_values[15][0], parameter_values[16][0], parameter_values[17][0]], 
                                 'b': [parameter_values[0][1], parameter_values[1][1], parameter_values[2][1], parameter_values[3][1], parameter_values[4][1], parameter_values[5][1], parameter_values[6][1], parameter_values[7][1], parameter_values[8][1], parameter_values[9][1], parameter_values[10][1], parameter_values[11][1], parameter_values[12][1], parameter_values[13][1], parameter_values[14][1], parameter_values[15][1], parameter_values[16][1], parameter_values[17][1]],
                                 'c': [parameter_values[0][2], parameter_values[1][2], parameter_values[2][2], parameter_values[3][2], parameter_values[4][2], parameter_values[5][2], parameter_values[6][2], parameter_values[7][2], parameter_values[8][2], parameter_values[9][2], parameter_values[10][2], parameter_values[11][2], parameter_values[12][2], parameter_values[13][2], parameter_values[14][2], parameter_values[15][2], parameter_values[16][2], parameter_values[17][2]],
                                 'd': [parameter_values[0][3], parameter_values[1][3], parameter_values[2][3], parameter_values[3][3], parameter_values[4][3], parameter_values[5][3], parameter_values[6][3], parameter_values[7][3], parameter_values[8][3], parameter_values[9][3], parameter_values[10][3], parameter_values[11][3], parameter_values[12][3], parameter_values[13][3], parameter_values[14][3], parameter_values[15][3], parameter_values[16][3], parameter_values[17][3]],
                                 'e': [parameter_values[0][4], parameter_values[1][4], parameter_values[2][4], parameter_values[3][4], parameter_values[4][4], parameter_values[5][4], parameter_values[6][4], parameter_values[7][4], parameter_values[8][4], parameter_values[9][4], parameter_values[10][4], parameter_values[11][4], parameter_values[12][4], parameter_values[13][4], parameter_values[14][4], parameter_values[15][4], parameter_values[16][4], parameter_values[17][4]],
                                 'g': [parameter_values[0][5], parameter_values[1][5], parameter_values[2][5], parameter_values[3][5], parameter_values[4][5], parameter_values[5][5], parameter_values[6][5], parameter_values[7][5], parameter_values[8][5], parameter_values[9][5], parameter_values[10][5], parameter_values[11][5], parameter_values[12][5], parameter_values[13][5], parameter_values[14][5], parameter_values[15][5], parameter_values[16][5], parameter_values[17][5]],
                                 'h': [parameter_values[0][6], parameter_values[1][6], parameter_values[2][6], parameter_values[3][6], parameter_values[4][6], parameter_values[5][6], parameter_values[6][6], parameter_values[7][6], parameter_values[8][6], parameter_values[9][6], parameter_values[10][6], parameter_values[11][6], parameter_values[12][6], parameter_values[13][6], parameter_values[14][6], parameter_values[15][6], parameter_values[16][6], parameter_values[17][6]],
                                 'i': [parameter_values[0][7], parameter_values[1][7], parameter_values[2][7], parameter_values[3][7], parameter_values[4][7], parameter_values[5][7], parameter_values[6][7], parameter_values[7][7], parameter_values[8][7], parameter_values[9][7], parameter_values[10][7], parameter_values[11][7], parameter_values[12][7], parameter_values[13][7], parameter_values[14][7], parameter_values[15][7], parameter_values[16][7], parameter_values[17][7]],
                                 }
   dataframe = DataFrame(parameter_values_to_export, columns= ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i'])
   append_df_to_excel('Test.xlsx', dataframe, 'SNR OP BL Parameters')
   print(dataframe)
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    from openpyxl import load_workbook

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except IOError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

def fitfunc_polynome_OP_BL(x ,a, b, c, d, e, g, h, i):
    return a*(np.power(x,7)) + b*(np.power(x,6))+ c*(np.power(x,5)) + d*(np.power(x,4)) + e*(np.power(x,3)) + g*(np.power(x,2)) + h*x +i



if __name__ == '__main__':

    print("\nFitting SNR_UV---------------------------------------------\n")
    snr_fitting_excel(18,11,8)

此错误有任何提示/备注/解决方案吗?

0 个答案:

没有答案