pandas给出了不支持的操作:在Excel文件中写入 Dataframe 的truncate()

wztqucjr  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(111)

我正在使用pandas将我的数据框写入Excel文件。我编写了一个函数,可以帮助我将数据框写入Excel文件。这是函数:

def touch_excel(
        df: pd.DataFrame,
        file_path: str,
        sheet_name: str = "Sheet1",
        add_df: pd.DataFrame = None):
    """
        this function concatenates two data frames (if given),
        and converts them into an Excel file at the given location

        Args:
            df (pandas.DataFrame): the data frame to be written into the Excel file
            file_path (str): the path to the Excel file
            sheet_name (str): the name of the sheet in the Excel file
            add_df (pandas.DataFrame): the additional data frame to be concatenated
    """
    if add_df is not None:
        df = pd.concat([df, add_df], ignore_index=True)

    try:
        if not os.path.exists(file_path):
            df.to_excel(file_path, sheet_name=sheet_name, index=False)
        else:
            with pd.ExcelWriter(file_path, mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
                df.to_excel(writer, sheet_name=sheet_name, index=False)
    except PermissionError:
        raise Exception("File might be open. Close it.")

字符串
现在,这个函数几乎在我所有的情况下运行,但在某些情况下,它给出了不支持的操作消息,并停止程序执行。为什么会发生这种情况?有人能解释一下吗?

Traceback (most recent call last):
  File "E:\Projects\PR-Dashboard-Automation\main.py", line 512, in <module>
    main()
  File "E:\Projects\PR-Dashboard-Automation\main.py", line 130, in main
    touch_excel(df, data_file, 'Previous Data')
  File "E:\Projects\PR-Dashboard-Automation\main.py", line 27, in touch_excel
    with pd.ExcelWriter(file_path, mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
  File "E:\Projects\PR-Dashboard-Automation\venv\Lib\site-packages\pandas\io\excel\_base.py", line 1370, in __exit__
    self.close()
  File "E:\Projects\PR-Dashboard-Automation\venv\Lib\site-packages\pandas\io\excel\_base.py", line 1374, in close
    self._save()
  File "E:\Projects\PR-Dashboard-Automation\venv\Lib\site-packages\pandas\io\excel\_openpyxl.py", line 113, in _save
    self._handles.handle.truncate()
io.UnsupportedOperation: truncate


我试图通过改变文件夹的路径来解决这个问题,我也试图使用其他方法,如手动设置工作簿。但它仍然没有解决这个问题。但每当我使用

mode = 'r'


而不是

mode = 'a'


它开始工作,但不会在同一个Excel文件中创建多个工作表。(问,因为这段代码运行几乎所有的程序,除了某些情况下)
提前感谢:)

kkbh8khc

kkbh8khc1#

OpenPyXL是否安装在您的系统中?
如果没有:

pip install openpyxl

字符串
如果是:

pip install --upgrade pandas openpyxl


而且,在这个代码块中:

else:
    with pd.ExcelWriter(file_path, mode='a', engine='openpyxl', 
        if_sheet_exists='replace') as writer:
            df.to_excel(writer, sheet_name=sheet_name, index=False)


你可以尝试将引擎类型从openpyxl更改为xlsxwriter,所以它将是这样的:

else:
    with pd.ExcelWriter(file_path, mode='a', engine='xlsxwriter', 
        if_sheet_exists='replace') as writer:
            df.to_excel(writer, sheet_name=sheet_name, index=False)

相关问题