Ошибка при попытке экспортировать фрейм данных pandas в файл excel

#python #pandas #export-to-excel

Вопрос:

Я пытаюсь отправить фрейм данных pandas в каталог C в виде файла excel

 df=pd.DataFrame([[1,3,5],[2,4,6]],index=['a1','a2'], columns=['b1','b2','b3'])
df.to_excel('C:/df1.xlsx',sheet_name='data')
 

Этот код выдает мне сообщение об ошибке, такое как

 PermissionError                           Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_13136/2106016881.py in <module>
----> 1 df.to_excel('C:/df1.xlsx',sheet_name='data')

~anaconda3libsite-packagespandascoregeneric.py in to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, verbose, freeze_panes, storage_options)
   2282             inf_rep=inf_rep,
   2283         )
-> 2284         formatter.write(
   2285             excel_writer,
   2286             sheet_name=sheet_name,

~anaconda3libsite-packagespandasioformatsexcel.py in write(self, writer, sheet_name, startrow, startcol, freeze_panes, engine, storage_options)
    832             # error: Cannot instantiate abstract class 'ExcelWriter' with abstract
    833             # attributes 'engine', 'save', 'supported_extensions' and 'write_cells'
--> 834             writer = ExcelWriter(  # type: ignore[abstract]
    835                 writer, engine=engine, storage_options=storage_options
    836             )

~anaconda3libsite-packagespandasioexcel_xlsxwriter.py in __init__(self, path, engine, date_format, datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs, **kwargs)
    189             raise ValueError("Append mode is not supported with xlsxwriter!")
    190 
--> 191         super().__init__(
    192             path,
    193             engine=engine,

~anaconda3libsite-packagespandasioexcel_base.py in __init__(self, path, engine, date_format, datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs, **kwargs)
    923         self.handles = IOHandles(cast(Buffer, path), compression={"copression": None})
    924         if not isinstance(path, ExcelWriter):
--> 925             self.handles = get_handle(
    926                 path, mode, storage_options=storage_options, is_text=False
    927             )

~anaconda3libsite-packagespandasiocommon.py in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
    708         else:
    709             # Binary mode
--> 710             handle = open(handle, ioargs.mode)
    711         handles.append(handle)
    712 

PermissionError: [Errno 13] Permission denied: 'C:/df1.xlsx'
 

Не совсем уверен, в чем причина проблемы
Кто-нибудь может мне помочь, как это решить?

Комментарии:

1. Большинство учетных записей Windows, не являющихся администраторами, не могут напрямую писать в » C:/». Попробуйте записать в свой обычный документ или рабочую папку.

Ответ №1:

Пожалуйста, убедитесь, что файл не открыт на вашем компьютере.

В то время как он открыт другим программным обеспечением, python не может получить к нему доступ, поэтому вы получаете Permission denied ошибку.